File tree Expand file tree Collapse file tree 1 file changed +55
-0
lines changed
Expand file tree Collapse file tree 1 file changed +55
-0
lines changed Original file line number Diff line number Diff line change 1+ ``` java
2+ import java.util.* ;
3+ import java.io.* ;
4+ public class Main {
5+ static BufferedReader br = new BufferedReader (new InputStreamReader (System . in));
6+ static BufferedWriter bw = new BufferedWriter (new OutputStreamWriter (System . out));
7+ static StringTokenizer st;
8+ static int N ,R ,Q ;
9+ static List<Integer > [] adjList;
10+ static int [] count;
11+ static boolean [] visited;
12+
13+
14+ public static void main (String [] args ) throws IOException {
15+ st = new StringTokenizer (br. readLine());
16+ N = Integer . parseInt(st. nextToken());
17+ R = Integer . parseInt(st. nextToken());
18+ Q = Integer . parseInt(st. nextToken());
19+
20+ adjList = new List [N + 1 ];
21+ for (int i = 1 ; i <= N ; i++ ) {
22+ adjList[i] = new ArrayList<> ();
23+ }
24+
25+ for (int i = 1 ; i < N ; i++ ) {
26+ st = new StringTokenizer (br. readLine());
27+ int u = Integer . parseInt(st. nextToken());
28+ int v = Integer . parseInt(st. nextToken());
29+ adjList[u]. add(v);
30+ adjList[v]. add(u);
31+ }
32+ count = new int [N + 1 ];
33+ visited = new boolean [N + 1 ];
34+ find(R );
35+
36+ for (int i = 0 ; i < Q ; i++ ) {
37+ int start = Integer . parseInt(br. readLine());
38+ bw. write(count[start] + " \n " );
39+ }
40+ bw. close();
41+ }
42+ static int find (int u ) {
43+ if (visited[u]) return 0 ;
44+ int cnt = 1 ;
45+ visited[u] = true ;
46+
47+ for (int v : adjList[u]) {
48+ cnt += find(v);
49+ }
50+ count[u] = cnt;
51+ return cnt;
52+ }
53+ }
54+
55+ ```
You can’t perform that action at this time.
0 commit comments