并查集入门题
注意:
最后遍历根的时候还要find一次
#include <iostream>
#include <vector>
#include <algorithm>
#include <unordered_set>
using namespace std;
const int N = 1e4+7;
int root[N];
int find(int x){
if(x == root[x]) return x;
else return root[x] = find(root[x]);
}
int main(){
int n, u, v;
cin>>n;
char c;
for(int i = 0; i <= n; i++){
root[i] = i;
}
getchar();
while(cin>>c){
if(c == 'S') break;
cin>> u>> v;
int a = find(u);
int b = find(v);
if(c == 'I'){
if(a != b){
root[b] = a;
}
}else{
if(a == b) cout<<"yes"<<endl;
else cout<<"no"<<endl;
}
}
unordered_set<int> st;
for(int i = 1; i <= n; i++){
st.insert(find(i));
}
if(st.size() == 1) cout<<"The network is connected."<<endl;
else cout<<"There are "<<st.size()<<" components."<<endl;
return 0;
}