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

 

PTA: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.

 

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<<"yesn";
            else cout<<"non";
        }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

原文链接: https://www.cnblogs.com/zlzhu/p/12259484.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

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

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/327112

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年3月1日 下午4:07
下一篇 2023年3月1日 下午4:08

相关推荐