-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprob_793.cc
More file actions
75 lines (68 loc) · 1.16 KB
/
prob_793.cc
File metadata and controls
75 lines (68 loc) · 1.16 KB
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
#include <iostream>
#include <vector>
#include <sstream>
using namespace std;
//solved
//basic idea is to implment union-find, include three functions:
//Union() to union two sets, findParent() and isSameSet();
int P[1000];
int R[1000];
int makeSet(int n){
for(int i=1; i<=n; i++){
P[i] = i;
R[i] =0;
}
}
int findParent(int n){
return (n ==P[n] ? n : findParent(P[n]));
}
bool isSameSet(int p, int k){
return (findParent(P[p]) == findParent(P[k]) ?true :false);
}
void Union(int p, int k){
if(findParent(P[p]) != findParent(P[k])){
p = findParent(P[p]);
k= findParent(P[k]);
if(R[p] >= R[k]){
R[p]++;
P[k] = p;
}
else {
R[k]++;
P[p] = k;
}
}
}
int main(){
int N;
cin >> N;
cin.ignore();
cin.ignore();
for(int x=0;x<N;x++){
string str;
int i=0;
int suc=0; int unsuc=0;
while(getline(cin, str)!=NULL && !str.empty()){
i++;
stringstream ss(str);
if(i==1){
int n;
ss>>n;
makeSet(n);
}
else {
int m,n;
char c;
ss>>c>>m>>n;
if(c=='c'){
Union(m,n);
}
else {
isSameSet(m,n) ? suc++ : unsuc++;
}
}
}
if(x>0) cout << endl;
cout << suc << "," << unsuc << endl;
}
}