Home BOJ. Tree (4803)
Post
Cancel

BOJ. Tree (4803)

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


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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import java.util.*;
import java.io.*;

public class Main {
	static BufferedReader br;
	static int max = 0, maxIdx = 0;
	public static void main(String[] args) throws IOException {
		br = new BufferedReader(new InputStreamReader(System.in));
		StringBuilder sb = new StringBuilder();
		String[] line;
		Node[] nodes;
		boolean[] visit;
		Node node;
		int cntTot = 0;
		int caseNum = 1;

		while(true) {
			line = getLine();
			int n = toi(line[0]), m = toi(line[1]), treeNum = 0;
			nodes = new Node[n];
			for(int i = 0; i < n; i++) nodes[i] = new Node(i);
			visit = new boolean[n];

			if(n == 0 && m == 0) break;

			for(int i = 0; i < m; i++) {
				line = getLine();
				int a = toi(line[0]) - 1, b = toi(line[1]) - 1;
				nodes[a].list.add(b);
				nodes[b].list.add(a);
			}

			Queue<Node> q =  new LinkedList<>();

			for(int i = 0; i < n; i++) {
				if(visit[i]) continue;
				q.clear();

				q.add(nodes[i]);
				treeNum += bfs(q, nodes, visit);
			}

			if(treeNum == 0) sb.append("Case " + caseNum + ": No trees.");
			else if(treeNum  == 1) sb.append("Case " + caseNum  + ": There is one tree.");
			else sb.append("Case " + caseNum + ": A forest of " + treeNum + " trees.");
			caseNum++;
			sb.append("\n");
		}
		print(sb);
	}

	static int bfs(Queue<Node> q, Node[] nodes, boolean[] visit) {
		int vCnt = 0, adjCnt = 0;
		while(!q.isEmpty()) {
			Node cur = q.poll();
			vCnt++;
			adjCnt += cur.list.size();
			if(visit[cur.idx]) continue;
			visit[cur.idx] = true;
			for(int e : cur.list) {
				if(visit[e]) continue;
				q.add(nodes[e]);
			}
		}
		if(adjCnt == 2 * vCnt - 2) return 1;
		return 0;
	}

	static class Node {
		int idx;
		ArrayList<Integer> list;

		public Node(int idx) { this.idx = idx; list = new ArrayList<>(); }
	}

	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.