模板题:并查集
题意:给你n个用户和m个组,让你求出如果第i个人传播消息,会有几个人知道。http://codeforces.com/contest/1167/problem/C
思路:简单的并查集
#include <cstdio> #include<bits/stdc++.h> const int maxnn = 3000000; using namespace std; typedef long long ll; int pre[600000]; int rank1[600000]; int _find(int x) { int a=x; while(x!=pre[x]) { x=pre[x]; rank1[a]++; } return x; } int _find1(int x) { int a=x; while(x!=pre[x]) { x=pre[x]; } return x; } int main() { int n,m; for(int i=0;i<600000;i++){pre[i]=i;rank1[i]=1;} scanf("%d%d",&n,&m); for(int i=0;i<m;i++) { int t; scanf("%d",&t); if(t==0)continue; int k,kk; scanf("%d",&k); for(int j=0;j<t-1;j++) { scanf("%d",&kk); int a=_find(k); int b=_find(kk); if(a!=b) { if(rank1[a]>rank1[b]) { pre[b]=a; rank1[a]+=rank1[b]; } else { pre[a]=b; rank1[b]+=rank1[a]; } } } } for(int i=1;i<=n;i++) { pre[i]=_find1(pre[i]); rank1[i]=rank1[_find(pre[i])]; } for(int i=1;i<=n;i++) { if(i==1)printf("%d",rank1[i]); else printf(" %d",rank1[i]); } return 0; }