[Link] https://www.acmicpc.net/problem/15681
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
56
57
58
import java.util.*;
import java.io.*;
public class Main {
static BufferedReader br;
static int max = 0, maxIdx = 0;
public static void main(String[] args) throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb = new StringBuilder();
int[] arr = getArr();
int n = arr[0], r = arr[1], query = arr[2];
int[] dp = new int[n + 1];
ArrayList<Node> al = new ArrayList<>();
al.add(null);
for(int i = 1; i <= n; i++) al.add(new Node(i));
for(int i = 0; i < n - 1; i++) {
arr = getArr();
int u = arr[0], v = arr[1];
al.get(u).child.add(v);
al.get(v).child.add(u);
}
getSubTreeNode(al, r, dp);
for(int i = 0; i < query; i++) {
int u = toi(br.readLine());
sb.append(dp[u]).append("\n");
}
print(sb);
}
static int getSubTreeNode(ArrayList<Node> al, int idx, int[] dp) {
if(dp[idx] != 0) return dp[idx];
int sum = 1;
for(int childIdx : al.get(idx).child) {
if(childIdx == al.get(idx).parent) continue;
Node childNode = al.get(childIdx);
childNode.parent = idx;
sum += getSubTreeNode(al, childIdx, dp);
}
return dp[idx] = sum;
}
static class Node {
int idx;
int parent;
ArrayList<Integer> child = new ArrayList<>();
public Node(int idx) { this.idx = idx; }
}
static int toi(String s) { return Integer.parseInt(s); }
static String[] getLine() throws IOException { return br.readLine().split(" "); }
static int[] getArr() throws IOException { return Arrays.stream(br.readLine().split(" ")).mapToInt(Integer::parseInt).toArray(); }
static <T> void print(T s) { System.out.print(s); }
static <T> void println(T s) { System.out.println(s); }
}