1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
| const int N = 1000, M = N * 2; int h[N], e[M], ne[M], idx; class Solution { public: int ans = 1e9; vector<int> w; void add(int u, int v) { e[idx] = v, ne[idx] = h[u], h[u] = idx++; } int dfs(int u, int f, int sumx, int sumy) { int res = w[u]; for (int i = h[u]; ~i; i = ne[i]) { int v = e[i]; if (v == f) continue; int t = dfs(v, u, sumx, sumy); res ^= t; if (sumx != -1) { int a[3] = {sumy, t, sumx ^ t}; sort(a, a + 3); ans = min(ans, a[2] - a[0]); } } return res; } int minimumScore(vector<int>& nums, vector<vector<int>>& edges) { int n = nums.size(); w = nums; for (int i = 0; i < n - 1; ++i) { memset(h, -1, n * 4); idx = 0; for (int j = 0; j < n - 1; ++j) { if (i != j) { int u = edges[j][0], v = edges[j][1]; add(u, v), add(v, u); } } int x = edges[i][0], y = edges[i][1]; int sumx = dfs(x, -1, -1, -1), sumy = dfs(y, -1, -1, -1); dfs(x, -1, sumx, sumy); dfs(y, -1, sumy, sumx); } return ans; } };
|