题目
We have a network of computers and a list of bi-directional connections. Each of these connections allows a file transfer from one computer to another. Is it possible to send a file from any computer on the network to any other?
Input Specification:
Each input file contains one test case. For each test case, the first line contains N (2≤N≤
1
0
4
10^4
104 ), the total number of computers in a network. Each computer in the network is then represented by a positive integer between 1 and N. Then in the following lines, the input is given in the format:I c1 c2
where I stands for inputting a connection between c1 and c2; orC c1 c2
where C stands for checking if it is possible to transfer files between c1 and c2; orS
where S stands for stopping this case.
Output Specification:
For each C case, print in one line the word “yes” or “no” if it is possible or impossible to transfer files between c1 and c2, respectively. At the end of each case, print in one line “The network is connected.” if there is a path between any pair of computers; or “There are k components.” where k is the number of connected components in this network.
Sample Input 1:
5
C 3 2
I 3 2
C 1 5
I 4 5
I 2 4
C 3 5
S
Sample Output 1:
no
no
yes
There are 2 components.
思路:
集合的操作用法,用数组表示集合,按秩合并,路径压缩。components在此题中表示联通集。即各自联通的划分为一个部分,共有几个部分。
code:
#include <iostream>
using namespace std;
int find(int a[],int x){//路径压缩
if(a[x]<0)
return x;
else return a[x]=find(a,a[x]);
}
int main(){
int n,a,b,cnt=0;//不是只有-1出现了才表示不联通;
cin>>n;
int ans[n+1];
for(int i=1;i<=n;i++) ans[i]=-1;
char c;
while(cin>>c){
if(c=='S') break;
cin>>a>>b;
if(c=='C'){//得看是否同根
a=find(ans,a);
b=find(ans,b);
a==b?cout<<"yes"<<endl:cout<<"no"<<endl;
}
else if(c=='I'){
a=find(ans,a);
b=find(ans,b);
if(a!=b){//不同根并,按秩合并
if(ans[a]<=ans[b]){
ans[a]+=ans[b];
ans[b]=a;
}
else{
ans[b]+=ans[a];
ans[a]=b;
}
}
}
}
for(int i=1;i<=n;i++)
if(ans[i]<0) cnt++;
cnt==1?cout<<"The network is connected."<<endl:cout<<"There are "<<cnt<<" components."<<endl;
return 0;
}