|
| 1 | +```java |
| 2 | + |
| 3 | +import java.util.*; |
| 4 | +import java.io.*; |
| 5 | + |
| 6 | + |
| 7 | +class Main { |
| 8 | + |
| 9 | + // IO field |
| 10 | + static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 11 | + static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); |
| 12 | + static StringTokenizer st = new StringTokenizer(""); |
| 13 | + |
| 14 | + static void nextLine() throws Exception {st = new StringTokenizer(br.readLine());} |
| 15 | + static int nextInt() throws Exception { |
| 16 | + if(!st.hasMoreTokens()) nextLine(); |
| 17 | + return Integer.parseInt(st.nextToken()); |
| 18 | + } |
| 19 | + static long nextLong() throws Exception { |
| 20 | + if(!st.hasMoreTokens()) nextLine(); |
| 21 | + return Long.parseLong(st.nextToken()); |
| 22 | + } |
| 23 | + static void bwEnd() throws Exception {bw.flush();bw.close();} |
| 24 | + |
| 25 | + // Additional field |
| 26 | + |
| 27 | + static int N; |
| 28 | + static int[] A; |
| 29 | + static long[] R, B, ans; |
| 30 | + static List<Integer>[] V; |
| 31 | + static long blue = 0, red = 0; |
| 32 | + |
| 33 | + public static void main(String[] args) throws Exception { |
| 34 | + |
| 35 | + ready(); |
| 36 | + solve(); |
| 37 | + |
| 38 | + bwEnd(); |
| 39 | + |
| 40 | + } |
| 41 | + |
| 42 | + static void ready() throws Exception{ |
| 43 | + |
| 44 | + N = nextInt(); |
| 45 | + A = new int[N+1]; |
| 46 | + for(int i=1;i<=N;i++) { |
| 47 | + A[i] = nextInt(); |
| 48 | + red += A[i] == 1 ? 1 : 0; |
| 49 | + blue += A[i] == 0 ? 1 : 0; |
| 50 | + } |
| 51 | + V = new List[N+1]; |
| 52 | + for(int i=1;i<=N;i++) V[i] = new ArrayList<>(); |
| 53 | + |
| 54 | + for(int i=1;i<N;i++) { |
| 55 | + int a = nextInt(), b = nextInt(); |
| 56 | + V[a].add(b); |
| 57 | + V[b].add(a); |
| 58 | + } |
| 59 | + |
| 60 | + R = new long[N+1]; |
| 61 | + B = new long[N+1]; |
| 62 | + ans = new long[N+1]; |
| 63 | + |
| 64 | + } |
| 65 | + |
| 66 | + static void solve() throws Exception{ |
| 67 | + |
| 68 | + dfs(1, 0); |
| 69 | + for(int Q=nextInt();Q-->0;) { |
| 70 | + int x = nextInt(); |
| 71 | + bw.write(ans[x] + "\n"); |
| 72 | + } |
| 73 | + |
| 74 | + } |
| 75 | + |
| 76 | + static void dfs(int n, int p) { |
| 77 | + |
| 78 | + for(int i:V[n]) if(i != p) { |
| 79 | + dfs(i, n); |
| 80 | + R[n] += R[i] + (A[i] == 1 ? 1 : 0); |
| 81 | + B[n] += B[i] + (A[i] == 0 ? 1 : 0); |
| 82 | + } |
| 83 | + ans[n] += R[n] * (blue - (B[n] + (A[n] == 0 ? 1 : 0))); |
| 84 | + ans[n] += B[n] * (red - (R[n] + (A[n] == 1 ? 1 : 0))); |
| 85 | + for(int i:V[n]) if(i != p) { |
| 86 | + ans[n] += (R[i] + (A[i] == 1 ? 1 : 0)) * (B[n] - (B[i] + (A[i] == 0 ? 1 : 0))); |
| 87 | + } |
| 88 | + |
| 89 | + } |
| 90 | + |
| 91 | +} |
| 92 | + |
| 93 | +``` |
0 commit comments