题目链接
解题思路:
并查集的应用
代码如下:
#include<iostream>
#include<algorithm>
#include<cstring>
#include<set>
using namespace std;
const int maxn=1e4+10;
set<int> s;
int f[maxn];
int a[maxn];
int find(int x)
{
if(f[x]==x)
return x;
else
{
f[x]=find(f[x]);
return f[x];
}
}
int hebing(int x,int y)
{
x=find(x);
y=find(y);
if(x!=y)
{
f[x]=y;
}
}
int main()
{
int n;
int ans=0;
int k,x,i,j,y,q;
for(i=1;i<maxn;i++)
f[i]=i;
cin>>n;
while(n--)
{
cin>>k;
for(i=0;i<k;i++)
{
cin>>a[i];
s.insert(a[i]);
hebing(a[0],a[i]);
}
}
cout<<s.size()<<" ";
for(i=1;i<=s.size();i++)
{
if(f[i]==i)
ans++;
}
cout<<ans<<endl;
cin>>q;
while(q--)
{
cin>>x>>y;
if(find(x)==find(y))
cout<<"Y"<<endl;
else
cout<<"N"<<endl;
}
return 0;
}