C. News Distribution
In some social network, there are n users communicating with each other in m groups of friends. Let’s analyze the process of distributing some news between users.
Initially, some user x 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 x you have to determine what is the number of users that will know the news if initially only user x starts distributing it.
Input
The first line contains two integers n and m (1≤n,m≤5⋅105) — the number of users and the number of groups of friends, respectively.
Then m lines follow, each describing a group of friends. The i-th line begins with integer ki (0≤ki≤n) — the number of users in the i-th group. Then ki distinct integers follow, denoting the users belonging to the i-th group.
It is guaranteed that ∑i=1mki≤5⋅105.
Output
Print n integers. The i-th integer should be equal to the number of users that will know the news if user i starts distributing it.
Examples
inputCopy
7 5
3 2 5 4
0
2 1 2
1 1
2 6 7
outputCopy
4 4 1 4 4 2 2
Hint
题意:
给你n个用户和m个组,让你求出如果第i个人传播消息,会有几个人知道。
题解:
其实就是求并查集里第 i 个节点在的那一大块共有几个节点, watch一下par数组就能很直观的看出来了
经验小结:
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <string>
#include <stdlib.h>
#include <vector>
#include <queue>
#include <cmath>
#include <stack>
#include <map>
#include <set>
using namespace std;
#define ms(x, n) memset(x,n,sizeof(x));
typedef long long LL;
const int inf = 1 << 30;
const LL maxn = 5*1e5 + 10;
int par[maxn], rak[maxn]; //par储存每个树的父亲, rank储存树的高度(根树)
void init(int n) {
//初始化n个元素
for(int i = 1; i <= n; i++)
par[i] = i, rak[i] = 0;
}
int findr(int x) {
//查询树的根
if(par[x] == x) //父节点即为根
return x;
else //向上查找根, 并路径压缩直接指向根
return par[x] = findr(par[x]);
}
bool isSame(int x, int y) {
//判断x和y是否属于同一集合
return findr(x) == findr(y);
}
void unite(int x, int y) {
//合并x和y所属的集合
x = findr(x);
y = findr(y);
if(x == y)
return; //同一个集
//合并时从rank小的向rank大的连
if(rak[x] < rak[y])
par[x] = y;
else {
par[y] = x;
if(rak[x] == rak[y])
rak[x]++; //如果rank相同则++
}
}
map<int, int> cnt;
int main() {
int n, m, k, a, b;
cin >> n >> m;
init(n);
for(int i = 1; i <= m; ++i){
cin >> k;
if(k>0) cin >> a;
for(int j = 2; j <= k; ++j){
cin >> b;
unite(a, b);
}
}
for(int i = 1; i <= n; ++i)
++cnt[findr(i)];
for(int i = 1; i <= n; ++i)
cout << cnt[findr(i)] << " ";
cout << endl;
return 0;
}