-
-
Notifications
You must be signed in to change notification settings - Fork 9k
/
Copy pathSolution.java
55 lines (52 loc) · 1.37 KB
/
Solution.java
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
45
46
47
48
49
50
51
52
53
54
55
class Solution {
private int s;
private int s1;
private int n;
private int ans = Integer.MAX_VALUE;
private int[] nums;
private List<Integer>[] g;
public int minimumScore(int[] nums, int[][] edges) {
n = nums.length;
g = new List[n];
this.nums = nums;
Arrays.setAll(g, k -> new ArrayList<>());
for (int[] e : edges) {
int a = e[0], b = e[1];
g[a].add(b);
g[b].add(a);
}
for (int v : nums) {
s ^= v;
}
for (int i = 0; i < n; ++i) {
for (int j : g[i]) {
s1 = dfs(i, -1, j);
dfs2(i, -1, j);
}
}
return ans;
}
private int dfs(int i, int fa, int x) {
int res = nums[i];
for (int j : g[i]) {
if (j != fa && j != x) {
res ^= dfs(j, i, x);
}
}
return res;
}
private int dfs2(int i, int fa, int x) {
int res = nums[i];
for (int j : g[i]) {
if (j != fa && j != x) {
int a = dfs2(j, i, x);
res ^= a;
int b = s1 ^ a;
int c = s ^ s1;
int t = Math.max(Math.max(a, b), c) - Math.min(Math.min(a, b), c);
ans = Math.min(ans, t);
}
}
return res;
}
}