案例4-1.7 文件传输

题目

当两台计算机双向连通的时候,文件是可以在两台机器间传输的。给定一套计算机网络,请你判断任意两台指定的计算机之间能否传输文件?

代码

#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);
}


总结

求联通使用了并查集,对于联通集的个数我才用了最笨的方法先用数组计数然后再遍历计数数组的方式,如果哪位大佬有比较好的解决方法,请留言谢谢。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值