-
Notifications
You must be signed in to change notification settings - Fork 0
/
UVa10538.java
92 lines (73 loc) · 1.93 KB
/
UVa10538.java
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
81
82
83
84
85
86
87
88
89
90
91
92
package com.company;
import java.util.Scanner;
import java.util.ArrayList;
public class Main {
static int arr[];
static int rank[];
public static void main(String[] args) {
// write your code here
Scanner keyboard = new Scanner(System.in);
int peopleNum , TeamNum , a , b ,p_a,p_b, groupCount , Case = 1;
while(keyboard.hasNextInt())
{
peopleNum = keyboard.nextInt();
TeamNum = keyboard.nextInt();
if ( peopleNum == 0 && TeamNum == 0)
break;
groupCount = peopleNum;
arr = new int[peopleNum+1];
rank = new int[peopleNum+1];
Init();
for(int i = 0 ; i < TeamNum ; i ++)
{
a = keyboard.nextInt();
b = keyboard.nextInt();
p_a = Find(a);
p_b = Find(b);
if(p_a != p_b){
Union(a,b,p_a,p_b);
groupCount -- ;
}
}
System.out.println("Case " + Case +": " + groupCount);
Case ++ ;
}
}
public static void Init()
{
for(int i = 0 ; i < arr.length ; i ++)
{
arr[i] = i ;
}
}
public static int Find(int node)
{
if (arr[node] == node)
return node;
return Find(arr[node]);
}
public static void Union(int a , int b , int root_a,int root_b)
{
int temp,root,sub;
if(rank[root_a] == rank[root_b]){
root = root_a;
sub = b;
rank[root] ++;
}
else if(rank[root_a] > rank[root_b]){
root = root_a;
sub = b;
}
else{
root = root_b;
sub = a;
}
while(sub != arr[sub])
{
temp = sub;
sub = arr[sub];
arr[temp] = root;
}
arr[sub] = root;
}
}