2020 GDUT Rating Contest IV F. News Distribution

F. News Distribution

link

Title Description
There are n individuals, they each added some group. M pieces of information about a given group who are. If a group of friends who joined another group, this person can be considered to join another group. Everyone output group number (default everyone has joined a group before giving information)

Topic analysis
because it is directly related to the transfer of people, and apply the disjoint-set template.

Code

#include <bits/stdc++.h>

using namespace std;

int root[500001],ans[500001];

int union_search(int x){
	int son=x,temp;
	while(root[x]!=x){
		x=root[x];
	}
	while(root[son]!=x){
		temp=son;
		son=root[son];
		root[temp]=x;
	}
	return x;
}

int main(){
	int n,m;
	cin>>n>>m;
	for(int i=1;i<=n;i++)
		root[i]=i;
	for(int i=0;i<m;i++){
		int member,first;
		scanf("%d",&member);
		if(member==0)
			continue;
		scanf("%d",&first);
		int root_first=union_search(first);
		for(int j=0;j<member-1;j++){
			int temp;
			scanf("%d",&temp);
			temp=union_search(temp);
			if(temp!=root_first){
				root[temp]=root_first;//是temp的根等于root_first而不是temp
				//printf("now,%d's father is %d\n",temp,root_first);
			}
		}
	}
	for(int i=1;i<=n;i++){
		union_search(i);
	}
	for(int i=1;i<=n;i++){
		ans[root[i]]++;
	}
	for(int i=1;i<=n;i++){
		//printf("%d's father is %d\n",i,root[i]);
		printf("%d",ans[root[i]]);
		if(i!=n)
			printf(" ");
		else
			printf("\n");
	}
}

Published 24 original articles · won praise 1 · views 598

Guess you like

Origin blog.csdn.net/palax0/article/details/104828642