浙大陈越数据结构-05-树8 File Transfer

//
// Created by lyx on 2023/5/8.
//
#include <iostream>
#include <vector>

using namespace std;

int find(vector<int>& findSet, int num){
    if(findSet[num] < 0)
        return num;
    else
        return findSet[num] = find(findSet, findSet[num]);
}

void connect(vector<int>& findSet, int root1, int root2){
    if(findSet[root1] < findSet[root2]){
        findSet[root1] += findSet[root2];
        findSet[root2] = root1;
    }
    else{
        findSet[root2] += findSet[root1];
        findSet[root1] = root2;
    }
}

int countComponents(vector<int>& findSet){
    int num = 0;
    for(int i = 0; i < findSet.size(); i++){
        if(findSet[i] < 0)
            num++;
    }
    return num;
}

int main(){
    int N;
    cin >> N;
    vector<int> findSet(N, -1);
    char option;
    cin >> option;
    while(option != 'S'){
        int num1, num2;
        cin >> num1 >> num2;
        if(option == 'C'){
            int root1 = find(findSet, num1 - 1);
            int root2 = find(findSet, num2 - 1);
            if(root1 == root2)
                cout << "yes"<<endl;
            else
                cout << "no" << endl;
        }
        else{
            int root1 = find(findSet, num1 - 1);
            int root2 = find(findSet, num2 - 1);
            if(root1 != root2){
                connect(findSet, root1, root2);
            }
        }
        cin >> option;
    }
    int components = countComponents(findSet);
    if(components == 1)
        cout << "The network is connected.";
    else
        cout << "There are "<<components <<" components.";

    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值