PTA:7-129 文件传输 (25分)--(并查集)

7-129 文件传输 (25分)

在这里插入图片描述
输入样例 1:
5
C 3 2
I 3 2
C 1 5
I 4 5
I 2 4
C 3 5
S

输出样例 1:
no
no
yes
There are 2 components.

输入样例 2:
5
C 3 2
I 3 2
C 1 5
I 4 5
I 2 4
C 3 5
I 1 3
C 1 5
S

输出样例 2:
no
no
yes
yes
The network is connected.

思路
利用并查集,每执行“I”操作时,就将两个计算机合并再一个网络中;“C”操作进行查询即可。
具体AC代码如下:

#include<bits/stdc++.h>
using namespace std;
int n,p[10009];
int find(int x){
	if(x==p[x]) return x;
	return p[x]=find(p[x]);
}

void merge(int x, int y){
	int xx=find(x), yy=find(y);
	if(xx!=yy) p[xx]=yy; 
}
 
int main(){
	cin>>n;
	for(int i=1; i<=n; i++) p[i]=i;
	getchar;
	char ch='a';
	int a,b;
	while(1){
		cin>>ch;
		if(ch=='S') break;
		cin>>a>>b;
		if(ch=='C'){
			if(find(a)==find(b)) cout<<"yes\n";
			else cout<<"no\n";
		}else if(ch=='I'){
			merge(a,b);
		}
	}
	int cnt=0;
	for(int i=1; i<=n; i++){
		if(i==find(i)) cnt++;
	}
	if(cnt==1) cout<<"The network is connected.\n";
	else cout<<"There are "<<cnt<<" components.\n";
	return 0;
}

欢迎大家批评改正!!!

发布了49 篇原创文章 · 获赞 2 · 访问量 3866

猜你喜欢

转载自blog.csdn.net/weixin_43581819/article/details/104119509
今日推荐