1107. Social Clusters (30)

来源:互联网 发布:德军总部剧情知乎 编辑:程序博客网 时间:2024/06/05 18:13

题目详情:https://www.patest.cn/contests/pat-a-practise/1107

提交:
这里写图片描述

提交代码:

#include <iostream>#include <vector>#include <algorithm>using namespace std;#define N 1010int hobby[N],likePerson[N];int n,isRoot[N];int findFather( int key ){    while( key != hobby[key] )        key = hobby[key];    return key;}void Union( int a,int b ){    a = findFather(a);    b = findFather(b);    if( a != b )        hobby[a] = b;}void Init(){    for( int i=1;i<=n;++i )    {        hobby[i] = i;        isRoot[i] = 0;    }}int main (){    cin>>n;    Init();    for( int i=1;i<=n;++i )    {        int h,num;        scanf("%d:",&num);        for( int j=1;j<=num;++j )        {            cin>>h;            if( likePerson[h] == 0 )                likePerson[h] = i;            Union(i,likePerson[h]);        }       }    for( int i=1;i<=n;++i )    {        ++isRoot[findFather(i)];    }    int ans = 0;    for( int i=1;i<=n;++i )    {        if( isRoot[i] != 0 )            ++ans;    }    cout<<ans<<endl;    sort(isRoot+1,isRoot+n+1); //从小到大     for( int i=n;i>n-ans;--i )    {        if( i == n-ans+1 )            cout<<isRoot[i]<<endl;        else            cout<<isRoot[i]<<" ";    }    return 0;}

我没想出来,看的算法笔记,功力还是太浅了。加油吧!

0 0
原创粉丝点击