传送门:Indirect Know
Indirect Know
Source : xiaoE | |||
Time limit : 3 sec | Memory limit : 64 M |
Submitted : 299, Accepted : 165
Background
New term comes. And the new students of HIT@CS have already been in school. Every new one has known several other new ones. Because of the memory power, they can't know everyone others, and every one at most know fifteen others. As we known, bin3 is a very very gossipy boy, he wants to count how many pairs of them is indirect known each other.
We define indirect known below:
If bin3 know wywcgs, then bin3 indirect know wywcgs;
If bin3 indirect know wywcgs, and wywcgs know L, then bin3 indirect know L;
bin3 indirect know L, that means L also indirect know bin3;
Input
There are several cases.In every case, the first line is a positive integer n(n ≤ 600), standing for the new students'number.Next comes n lines, and in line i, first integer ki is the students'number that i know, next ki integers stand for the student i know. Here i from 0 to n-1.
Output
Only one integer stands for the number of pairs with indirect-know relation.
Sample Input
5 2 1 2 1 0 1 0 1 4 1 3
Sample Output
4
解题报告:
基础并查集。代码如下:
#include<iostream>
#include<cstdio>
using namespace std;
int father[605],num[605];
int n,m;
void makeset(int n){
for(int j=0;j<n;j++){
father[j]=j;
num[j]=1;
}
}
int findset(int x){
return father[x]==x?x:father[x]=findset(father[x]);
}
void Union(int a,int b){
int x=findset(a);
int y=findset(b);
if(x==y)
return;
if(num[x]<=num[y]){
father[x]=y;
num[y]+=num[x];
}
else{
father[y]=x;
num[x]+=num[y];
}
}
int main(){
int ans;
while(scanf("%d",&n)==1){
ans=0;
makeset(n);
int a;
for(int i=0;i<n;i++){
scanf("%d",&m);
for(int j=0;j<m;j++){
scanf("%d",&a);
Union(i,a);
}
}
for(int i=0;i<n-1;i++)
for(int j=i+1;j<n;j++)
if(findset(i)==findset(j))
ans++;
printf("%d\n",ans);
}
return 0;
}