-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path05_3.cpp
More file actions
66 lines (60 loc) · 1.47 KB
/
Copy path05_3.cpp
File metadata and controls
66 lines (60 loc) · 1.47 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
#include <stdio.h>
#define ElementType int
typedef struct{
ElementType Data;
int Parent;
}SetType;
int Find( SetType S[], ElementType X);
void Union(SetType S[], ElementType X1, ElementType X2);
int main(){
int N;
scanf("%d", &N);
SetType S[N];
for(int i=0; i<N; ++i){
S[i].Data = i+1;
S[i].Parent = -1;
}
while(1){
char op;
ElementType c1, c2;
scanf(" %c", &op);
if(op=='S'){
int cnt = 0;
for(int i=0; i<N; ++i){
if(S[i].Parent<0) ++cnt;
}
if(cnt>1) printf("There are %d components.\n", cnt);
else printf("The network is connected.\n");
break;
}
scanf("%d %d", &c1, &c2);
if(op=='C'){
if(Find(S, c1) == Find(S, c2)) printf("yes\n");
else printf("no\n");
}else if(op=='I'){
Union(S, c1, c2);
}
}
return 0;
}
int Find( SetType S[], ElementType X){
// int i;
// for(i=0; i<N && S[i].Data!=X; ++i);
int i = X-1;
for( ; S[i].Parent>=0; i=S[i].Parent);
return i;
}
void Union(SetType S[], ElementType X1, ElementType X2){
int Root1, Root2;
Root1 = Find(S, X1);
Root2 = Find(S, X2);
// S[Root2].Parent = Root1;
if(S[Root1].Parent<S[Root2].Parent){
S[Root1].Parent += S[Root2].Parent;
S[Root2].Parent = Root1;
}
else{
S[Root2].Parent += S[Root1].Parent;
S[Root1].Parent = Root2;
}
}