并查集(算法描述)

例题:

C. News Distribution(第一次打)
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

In some social network, there are nn users communicating with each other in mm groups of friends. Let's analyze the process of distributing some news between users.

Initially, some user xx receives the news from some source. Then he or she sends the news to his or her friends (two users are friends if there is at least one group such that both of them belong to this group). Friends continue sending the news to their friends, and so on. The process ends when there is no pair of friends such that one of them knows the news, and another one doesn't know.

For each user xx you have to determine what is the number of users that will know the news if initially only user xx starts distributing it.

Input

The first line contains two integers nn and mm (1n,m51051≤n,m≤5⋅105) — the number of users and the number of groups of friends, respectively.

Then mm lines follow, each describing a group of friends. The ii-th line begins with integer kiki (0kin0≤ki≤n) — the number of users in the ii-th group. Then kiki distinct integers follow, denoting the users belonging to the ii-th group.

It is guaranteed that i=1mki5105∑i=1mki≤5⋅105.

Output

Print nn integers. The ii-th integer should be equal to the number of users that will know the news if user ii starts distributing it.

Example
input
7 5
3 2 5 4
0
2 1 2
1 1
2 6 7
output
4 4 1 4 4 2 2 

//对于多个关系类题目,考虑并查集和图论
#include 

using namespace std;
int a[(int)5e5+5];
int b[(int)5e5+5];
int get(int t)//查找祖先
{
    if(t==a[t])return t;
    else
      return  a[t]=get(a[t]);
}
//压行:
//int get(int t )
//{ return a[t]==t? t:a[t]=get(a[t]);}
void memge(int x,int y)//连接
{
    a[get(x)]=get(y);
}
int main ()
{
    int n,m;
    scanf("%d%d",&n,&m);
    for(int i=1;i<=n;i++)
        a[i]=i;
    while(m--)
    {
        int s,c;
        scanf("%d",&s);
        if(s==0)
            continue;
        else if(s==1)
            scanf("%d",&c);
        else
        {
            int j,k;
            scanf("%d",&j);
            for(int i=1;i) {
                scanf("%d",&k);
                memge(j, k);
            }
        }
    }
    for(int i=1;i<=n;i++)
        b[get(i)]++;//不能用啊b[a[i]]代替,因为存在有的点的父亲没有进行更新(通过查询最为保险)
for(int i=1;i<=n;i++)
printf(
"%d ",b[get(i)]);//不能用啊b[a[i]]代替,因为存在有的点的父亲没有进行更新(通过查询最为保险)

return 0; }

就是对于存在关系的一群点用一个点来进行代表;

转载于:https://www.cnblogs.com/zwx7616/p/10878058.html

你可能感兴趣的:(并查集(算法描述))