例题:
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.
The first line contains two integers nn and mm (1≤n,m≤5⋅1051≤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 (0≤ki≤n0≤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=1mki≤5⋅105∑i=1mki≤5⋅105.
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.
7 5
3 2 5 4
0
2 1 2
1 1
2 6 7
4 4 1 4 4 2 2
//对于多个关系类题目,考虑并查集和图论
#include <cstdio> 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<s;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; }
就是对于存在关系的一群点用一个点来进行代表;