码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2020-02-04 15:44:45      阅读:131      评论:0      收藏:0      [点我收藏+]

标签:names   etc   参考   else   ima   nts   mic   ==   for   

 

技术图片

 

 

输入样例 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.

 

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

参考链接:https://blog.csdn.net/weixin_43581819/article/details/104119509

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

标签:names   etc   参考   else   ima   nts   mic   ==   for   

原文地址:https://www.cnblogs.com/zlzhu/p/12259484.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!