[并查集]HOJ 2745 Indirect Know

传送门:Indirect Know

Indirect Know

My Tags  (Edit)
  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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值