有更好方法的同伴可以讨论下,代码如下:
include [HTML_REMOVED]
include [HTML_REMOVED]
using namespace std;
const int N = 10005;
int pre[N],temp[N];
set[HTML_REMOVED] num;
int find(int x){
if(x!=pre[x]) pre[x]=find(pre[x]);
return pre[x];
}
void Union(int x,int y)
{
int fx = find(x);
int fy = find(y);
if(fx<fy) pre[fx] = fy;
if(fy<fx) pre[fy] = fx;
return;
}
int main(){
for(int i=0;i[HTML_REMOVED]> n;
while(n–){
int m;
cin >> m;
for(int i=0;i[HTML_REMOVED]> x;
temp[i] = x;
num.insert(x);
if(i>0) Union(temp[i], temp[i-1]);
}
}
int num1 = 0;
for(int i=1;i<=num.size();i)
if(i==find(i)) num1;
cout << num.size() << " " << num1 << endl;
int q;
cin >> q;
for(int i=0;i<q;i++)
{
int x,y;
cin >> x >> y;
if(find(x)==find(y)) cout << "Y\n";
else cout << "N\n";
}
return 0;
}