案例4-1.7 文件传输 (25 分)
简单的并查集
#include<iostream>
#include<set>
using namespace std;
int fa[10010];
set<int> s;
int find(int x)
{
if(fa[x]==x)
return x;
else
return fa[x]=find(fa[x]);
}
int main()
{
int n,x,y;
char c;
cin>>n;
for(int i=1;i<=n;++i)
fa[i]=i;
while(cin>>c)
{
if(c=='S')
{
for(int i=1;i<=n;++i)
s.insert(find(i));
if(s.size()==1)
cout<<"The network is connected.";
else
cout<<"There are "<<s.size()<<" components.";
break;
}
cin>>x>>y;
if(c=='I')
{
x=find(x);
y=find(y);
if(x==y) continue;
fa[y]=x;
}
if(c=='C')
{
if(find(x)==find(y))
cout<<"yes"<<endl;
else
cout<<"no"<<endl;
}
}
}