//
// 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;
}
浙大陈越数据结构-05-树8 File Transfer
于 2023-05-08 12:01:01 首次发布