显示代码纯文本
#include<cstdio>
int ufs[500];
bool link[500][500];
int find(int x){
return x==ufs[x]?x:ufs[x]=find(ufs[x]);
}
void merge(int a,int b){
ufs[find(a)]=find(b);
}
int main(){
freopen("victoria2.in","r",stdin);
freopen("victoria2.out","w",stdout);
int n;scanf("%d",&n);
int tmp;
for(int i=1;i<=n;++i){
while(scanf("%d",&tmp),tmp!=0){
link[i][tmp]=true;
}
ufs[i]=i;
}
for(int k=1;k<=n;++k)
for(int i=1;i<=n;++i)
for(int j=1;j<=n;++j){
link[i][j]=link[i][j]|(link[i][k]&link[k][j]);
}
int ans=n;
for(int i=1;i<=n;++i){
for(int j=i+1;j<=n;++j){
if(link[i][j]&&link[j][i]&&find(i)!=find(j)){
ans--;
merge(i,j);
}
}
}
printf("%d",ans);
fclose(stdin);fclose(stdout);
return 0;
}