Home BOJ. Find Parent In Tree (11725)
Post
Cancel

BOJ. Find Parent In Tree (11725)

[Link] https://www.acmicpc.net/problem/11725


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import java.util.*;
import java.io.*;

public class Main {
	static BufferedReader br;
	public static void main(String[] args) throws IOException {
		br = new BufferedReader(new InputStreamReader(System.in));
		String[] line;
		StringBuilder sb = new StringBuilder();
		int n = toi(br.readLine());
		int[] parent = new int[n];
		boolean[] visit = new boolean[n];
		ArrayList<Node> al = new ArrayList<>();
		for(int i = 0; i < n; i++) al.add(new Node(i));

		for(int i = 1; i < n; i++) {
			line = getLine();
			int v1 = toi(line[0]) - 1, v2 = toi(line[1]) - 1;
			al.get(v1).list.add(v2);
			al.get(v2).list.add(v1);
		}
		Queue<Integer> q = new LinkedList<>();
		q.add(0);

		while(!q.isEmpty()) {
			int cur = q.poll();
			if(visit[cur]) continue;
			visit[cur] = true;
			for(int nodeIdx : al.get(cur).list) {
				if(visit[nodeIdx]) continue;
				parent[nodeIdx]  = cur;
				q.add(nodeIdx);
			}
		}

		for(int i = 1; i < n; i++) sb.append(parent[i] + 1).append("\n");
		print(sb);
	}

	static class Node {
		int idx;
		ArrayList<Integer> list = new ArrayList<>();

		Node(int idx) { this.idx =  idx; }
	}

	static int sum(int[] arr, int s, int e) { int sum = 0; for(int i = s; i <= e; i++) sum+=arr[i]; return sum; }
	static int toi(String s) { return Integer.parseInt(s); }
	static String[] getLine() throws IOException { return br.readLine().split(" "); }
	static <T> void print(T s) { System.out.print(s); }
	static <T> void println(T s) { System.out.println(s); }
}
This post is licensed under CC BY 4.0 by the author.