|
| 1 | +```java |
| 2 | +import java.io.*; |
| 3 | +import java.util.ArrayList; |
| 4 | +import java.util.List; |
| 5 | +import java.util.StringTokenizer; |
| 6 | + |
| 7 | +public class BJ_15681_트리와_쿼리 { |
| 8 | + |
| 9 | + private static final BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 10 | + private static final BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); |
| 11 | + private static final StringBuilder sb = new StringBuilder(); |
| 12 | + private static StringTokenizer st; |
| 13 | + |
| 14 | + private static int N; |
| 15 | + private static int R; |
| 16 | + private static int Q; |
| 17 | + |
| 18 | + private static int[] dp; |
| 19 | + private static boolean[] visited; |
| 20 | + private static List<Integer>[] tree; |
| 21 | + |
| 22 | + public static void main(String[] args) throws IOException { |
| 23 | + init(); |
| 24 | + sol(); |
| 25 | + } |
| 26 | + |
| 27 | + private static void init() throws IOException { |
| 28 | + st = new StringTokenizer(br.readLine()); |
| 29 | + |
| 30 | + N = Integer.parseInt(st.nextToken()); |
| 31 | + R = Integer.parseInt(st.nextToken()); |
| 32 | + Q = Integer.parseInt(st.nextToken()); |
| 33 | + |
| 34 | + tree = new List[N + 1]; |
| 35 | + for (int i = 1; i <= N; i++) { |
| 36 | + tree[i] = new ArrayList<>(); |
| 37 | + } |
| 38 | + |
| 39 | + for (int i = 0; i < N - 1; i++) { |
| 40 | + st = new StringTokenizer(br.readLine()); |
| 41 | + int u = Integer.parseInt(st.nextToken()); |
| 42 | + int v = Integer.parseInt(st.nextToken()); |
| 43 | + |
| 44 | + tree[u].add(v); |
| 45 | + tree[v].add(u); |
| 46 | + } |
| 47 | + visited = new boolean[N + 1]; |
| 48 | + dp = new int[N + 1]; |
| 49 | + } |
| 50 | + |
| 51 | + private static void sol() throws IOException { |
| 52 | + dp[R] = makeDP(R); |
| 53 | + |
| 54 | + for (int i = 0; i < Q; i++) { |
| 55 | + int q = Integer.parseInt(br.readLine()); |
| 56 | + |
| 57 | + sb.append(dp[q]).append("\n"); |
| 58 | + } |
| 59 | + bw.write(sb.toString()); |
| 60 | + bw.flush(); |
| 61 | + bw.close(); |
| 62 | + br.close(); |
| 63 | + } |
| 64 | + |
| 65 | + private static int makeDP(int parent) { |
| 66 | + if (dp[parent] != 0) return dp[parent]; |
| 67 | + |
| 68 | + int cnt = 1; |
| 69 | + for (int i = 0; i < tree[parent].size(); i++) { |
| 70 | + int child = tree[parent].get(i); |
| 71 | + |
| 72 | + if (visited[child] || child == R) { |
| 73 | + continue; |
| 74 | + } |
| 75 | + |
| 76 | + visited[child] = true; |
| 77 | + dp[child] = makeDP(child); |
| 78 | + cnt += dp[child]; |
| 79 | + } |
| 80 | + return cnt; |
| 81 | + } |
| 82 | + |
| 83 | +} |
| 84 | +``` |
0 commit comments