-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcutdrope.txt
executable file
·50 lines (40 loc) · 934 Bytes
/
cutdrope.txt
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
import java.util.ArrayList;
import java.util.Scanner;
public class Solution {
static int n;
static int a[];
static ArrayList<Integer> e[];
static int ans = Integer.MAX_VALUE;
static int sum = 0;
static int dfs(int u, int parent) {
int acc = a[u];
for (int v : e[u]) {
if (v == parent) continue;
int cb = dfs(v, u);
acc += cb;
ans = Math.min(ans, Math.abs(cb - (sum - cb)));
}
return acc;
}
@SuppressWarnings("unchecked")
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner cin = new Scanner(System.in);
n = cin.nextInt();
a = new int[n];
e = new ArrayList[n];
for (int i=0; i<n; i++) {
a[i] = cin.nextInt();
sum += a[i];
e[i] = new ArrayList<Integer>();
}
for (int i=0; i<n-1; i++) {
int u = cin.nextInt() - 1;
int v = cin.nextInt() - 1;
e[u].add(v);
e[v].add(u);
}
dfs(0, -1);
System.out.println(ans);
}
}