공부공간

BOJ - 15681 ) 트리와 쿼리 본문

알고리즘/Dynamic Programming

BOJ - 15681 ) 트리와 쿼리

개발자가될수있을까? 2021. 7. 26. 19:44


https://www.acmicpc.net/problem/15681

 

15681번: 트리와 쿼리

트리의 정점의 수 N과 루트의 번호 R, 쿼리의 수 Q가 주어진다. (2 ≤ N ≤ 105, 1 ≤ R ≤ N, 1 ≤ Q ≤ 105) 이어 N-1줄에 걸쳐, U V의 형태로 트리에 속한 간선의 정보가 주어진다. (1 ≤ U, V ≤ N, U ≠ V)

www.acmicpc.net


루트노드가 정해졌으므로 루트노드부터 재귀탐색을 하며 

 

하위 노드의 개수를 저장한다. 리프 노드의 경우 1로 간주한다.

 

따라서, 자신과 연결된 노드들의 값 +1을 현재에 값에 저장시키며 재귀탐색을 진행한다.


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.StringTokenizer;

public class Main {
	public static int[] cost ;
	public static boolean[] visit ;
	public static ArrayList<Integer> node[];
	public static void main(String[] args) throws Exception {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st = new StringTokenizer(br.readLine());
		int N = Integer.parseInt(st.nextToken());
		int R = Integer.parseInt(st.nextToken())-1;
		int Q = Integer.parseInt(st.nextToken());
		cost = new int[N];
		visit= new boolean[N];
		node = new ArrayList[N];
		for(int i=0;i<N;i++){node[i] = new ArrayList<>();}
		for(int i=0;i<N-1;i++){
			st = new StringTokenizer(br.readLine());
			int s = Integer.parseInt(st.nextToken())-1;
			int e = Integer.parseInt(st.nextToken())-1;
			node[s].add(e); node[e].add(s);
		}
		DFS(R);
		StringBuilder sb = new StringBuilder();
		for(int i=0;i<Q;i++) {sb.append(1+cost[Integer.parseInt(br.readLine())-1]).append("\n");}
		System.out.println(sb.toString());
	}
	private static int DFS(int now) {
		visit[now] = true;
		for(int i=0;i<node[now].size();i++) {
			if(!visit[node[now].get(i)]) {
				cost[now] += DFS(node[now].get(i));
			}
		}
		return cost[now]+1;
	}
}

'알고리즘 > Dynamic Programming' 카테고리의 다른 글

BOJ - 17069 ) 파이프 옮기기 2  (0) 2022.04.13
BOJ-17626 ) Four Squares  (0) 2022.03.02
BOJ - 10211 ) Maximum Subarray  (0) 2020.11.16
BOJ - 1520 ) 내리막길  (0) 2020.08.27
BOJ - 9252 ) LCS 2  (0) 2020.08.25
Comments