From defda6b1d1073699c1af08e8aabe4d245e6b4702 Mon Sep 17 00:00:00 2001 From: songyc macbook Date: Sun, 23 Nov 2025 20:00:08 +0900 Subject: [PATCH] 20251123 baekjoon --- code_study/Baekjoon/java/_15681.java | 54 ++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 code_study/Baekjoon/java/_15681.java diff --git a/code_study/Baekjoon/java/_15681.java b/code_study/Baekjoon/java/_15681.java new file mode 100644 index 0000000..7a43b4e --- /dev/null +++ b/code_study/Baekjoon/java/_15681.java @@ -0,0 +1,54 @@ +import java.util.*; + +class Tree { + private int root; + private ArrayList[] 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