2020 GDUT Rating Contest IV (Div. 2) F. News Distribution

来源:codeforces 2020 GDUT Rating Contest IV (Div. 2) CF链接

题目
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⋅1e5) — 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⋅1e5.

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.

Example
inputCopy
7 5
3 2 5 4
0
2 1 2
1 1
2 6 7
outputCopy
4 4 1 4 4 2 2

题意:n个人,m个组别,一个人知道某个新闻后会转发到自己在的所有组别,该组别的人也会进行相同操作,问第i个人最多能传播几个人。
思路:明显用并查集,用ans[find(i)]保存第i个人所在组的答案。注意一个组可能一个人都没有,注意要路径压缩,否则tle26

代码:

#include<iostream>
#include<cstdio>
#include<cmath>
#include<algorithm>
#include<cstring>
#define INF 0x3f3f3f3f
#define mod 1000000007
using namespace std;
int n,m,pre[500010],k,ans[500010];

int find(int x)
{
	if (pre[x]==x)
	return x;
	else pre[x]=find(pre[x]);
	return pre[x];
}
void join(int a,int b)
{
	int x=find(a),y=find(b);
	if (x!=y)
		pre[x]=y;
}
int main()
{
	cin>>n>>m;
	for (int i=1;i<=n;i++) pre[i]=i;
	for (int i=1;i<=m;i++)
	{
		scanf("%d",&k);
		if (!k) continue;
		int a,b;
		scanf("%d",&a);
		for (int j=1;j<k;j++)
		{
			scanf("%d",&b);
			join(a,b);
		}
	}
	for (int i=1;i<=n;i++)
		ans[find(i)]++;
	for (int i=1;i<=n;i++)
		printf("%d ",ans[find(i)]);
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值