题目
当两台计算机双向连通的时候,文件是可以在两台机器间传输的。给定一套计算机网络,请你判断任意两台指定的计算机之间能否传输文件?
代码
#include<stdio.h>
#include<stdlib.h>
#define N 100
int find(int x);
void unio(int x,int y);
int countLink();
int fa[N],count[N];
int n;
void main(){
int i;
char temp;
int vi,vj;
scanf("%d",&n);
getchar();
for(i=1;i<=n;i++)//初始化fa[]数组
fa[i]=i;
while(1){
scanf("%c",&temp);
if(temp=='S'){
if(countLink()>1){
printf("There are %d components.\n",countLink());
}else if(countLink()==1)
printf("The network is connected.\n");
break;
}
if(temp=='C'){
scanf("%d %d",&vi,&vj);
getchar();
if(find(vi)==find(vj)){
printf("YES\n");
}
else
printf("NO\n");
}
if(temp=='I'){
scanf("%d %d",&vi,&vj);
getchar();
unio(vi,vj);
}
}
system("pause");
}
int countLink(){
int i,cnt=0;
for(i=1;i<=n;i++){
count[i]=0;
}
for(i=1;i<=n;i++){
if(!count[find(i)])
count[find(i)]++;
}
for(i=1;i<=n;i++)
if(count[i])
cnt++;
return cnt;
}
//以下两个方法为并查集
int find(int x){
return x==fa[x]?x:(fa[x]=find(fa[x]));
}
void unio(int x,int y){
fa[find(x)]=find(y);
}
总结
求联通使用了并查集,对于联通集的个数我才用了最笨的方法先用数组计数然后再遍历计数数组的方式,如果哪位大佬有比较好的解决方法,请留言谢谢。