|
| 1 | +```java |
| 2 | +import java.util.*; |
| 3 | +import java.io.*; |
| 4 | + |
| 5 | +public class Main{ |
| 6 | + static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 7 | + static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); |
| 8 | + static StringTokenizer st; |
| 9 | + static StringBuilder sb = new StringBuilder(); |
| 10 | + static int N,M; |
| 11 | + static int T; |
| 12 | + public static void main(String[] args) throws Exception { |
| 13 | + T = 1; |
| 14 | + while(true){ |
| 15 | + st = new StringTokenizer(br.readLine()); |
| 16 | + N = Integer.parseInt(st.nextToken()); |
| 17 | + M = Integer.parseInt(st.nextToken()); |
| 18 | + if(N == 0 && M == 0) break; |
| 19 | + sb.append("Case ").append(T++).append(": " ); |
| 20 | + |
| 21 | + int[] parent = new int[N+1]; |
| 22 | + for (int i = 1; i <= N; i++) { |
| 23 | + parent[i] = i; |
| 24 | + } |
| 25 | + |
| 26 | + Set<Integer> cycles = new HashSet<>(); |
| 27 | + |
| 28 | + for (int i = 0; i < M; i++) { |
| 29 | + st = new StringTokenizer(br.readLine()); |
| 30 | + int a = Integer.parseInt(st.nextToken()); |
| 31 | + int b = Integer.parseInt(st.nextToken()); |
| 32 | + union(a, b, parent, cycles); |
| 33 | + } |
| 34 | + |
| 35 | + Set<Integer> s = new HashSet<>(); |
| 36 | + for (int i = 1; i <= N; i++) { |
| 37 | + s.add(find(i,parent)); |
| 38 | + } |
| 39 | + |
| 40 | + for(int c : cycles){ |
| 41 | + s.remove(find(c,parent)); |
| 42 | + } |
| 43 | + |
| 44 | + if(s.size()==0){ |
| 45 | + sb.append("No trees.\n"); |
| 46 | + }else if(s.size()==1){ |
| 47 | + sb.append("There is one tree.\n"); |
| 48 | + }else{ |
| 49 | + sb.append("A forest of ").append(s.size()).append(" trees.\n"); |
| 50 | + } |
| 51 | + } |
| 52 | + bw.write(sb.toString()); |
| 53 | + bw.close(); |
| 54 | + } |
| 55 | + public static int find(int cur, int[] parent){ |
| 56 | + if(parent[cur] == cur) return cur; |
| 57 | + else return parent[cur] = find(parent[cur],parent); |
| 58 | + } |
| 59 | + public static void union(int a, int b, int[] parent, Set<Integer> cycles){ |
| 60 | + int rootA = find(a,parent); |
| 61 | + int rootB = find(b,parent); |
| 62 | + |
| 63 | + if(rootA < rootB){ |
| 64 | + parent[rootA] = rootB; |
| 65 | + }else if(rootA > rootB){ |
| 66 | + parent[rootB] = rootA; |
| 67 | + }else{ |
| 68 | + cycles.add(rootA); |
| 69 | + } |
| 70 | + } |
| 71 | +} |
| 72 | +``` |
0 commit comments