20251123 baekjoon

This commit is contained in:
songyc macbook 2025-11-23 20:00:08 +09:00
parent 19013cb1f5
commit defda6b1d1

View File

@ -0,0 +1,54 @@
import java.util.*;
class Tree {
private int root;
private ArrayList<Integer>[] edges;
private int[] subTreeSizes;
private boolean[] visited;
public Tree(int root, int treeSize) {
this.root = root;
this.subTreeSizes = new int[treeSize+1];
this.visited = new boolean[treeSize+1];
this.edges = new ArrayList[treeSize + 1];
for(int i=0; i<=treeSize; i++) this.edges[i] = new ArrayList<>();
}
public void addEdge(int u, int v) {
this.edges[u].add(v);
this.edges[v].add(u);
}
public void printSubTreeSize(int node) {
System.out.println(this.subTreeSizes[node]);
}
public void countSubTreeSizes() {
this.dfs(root);
}
private void dfs(int current) {
this.visited[current] = true;
this.subTreeSizes[current] = 1;
for (int next : this.edges[current]) {
if(!this.visited[next]) {
dfs(next);
this.subTreeSizes[current] += this.subTreeSizes[next];
}
}
}
}
public class _15681 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt(), R = sc.nextInt(), Q = sc.nextInt();
Tree tree = new Tree(R, N);
for(int i=0; i<N-1; i++) tree.addEdge(sc.nextInt(), sc.nextInt());
tree.countSubTreeSizes();
for(int i=0; i<Q; i++) tree.printSubTreeSize(sc.nextInt());
sc.close();
}
}