标签:
Time Limit:1000MS Memory Limit:102400KB 64bit IO Format:%I64d & %I64
Description
Input
Output
Sample Input
Sample Output
Hint
A and B are friends(direct or indirect), B and C are friends(direct or indirect), then A and C are also friends(indirect).
In the first sample {1,2,5,6} is the result. In the second sample {1,2},{3,4},{5,6},{7,8} are four kinds of answers.
题意:朋友和朋友住在一起,不是朋友的不能住在一起,A与B是朋友,B与C是朋友,则A与C也是朋友,问最大朋友数。
分析:典型并查集。
1 #include<cstdio> 2 #include<cstring> 3 #include<iostream> 4 5 using namespace std; 6 7 int s[10000005]; 8 int sum[10000005]; 9 int maxn; 10 11 int find(int x) 12 { 13 return s[x]==x?x:find(s[x]); 14 } 15 16 void init () 17 { 18 maxn=1;//注意这里最小人数一定是 1 19 for(int i=0;i<=10000000;i++) 20 { 21 s[i]=i; 22 sum[i]=1; 23 } 24 } 25 26 void merge(int a,int b) 27 { 28 a=find(a); 29 b=find(b); 30 if(a==b) return; 31 if(sum[a]>=sum[b]) 32 { 33 s[b]=a; 34 sum[a]+=sum[b]; 35 if(maxn<sum[a]) maxn=sum[a]; 36 } 37 else 38 { 39 s[a]=b; 40 sum[b]+=sum[a]; 41 if(maxn<sum[b]) maxn=sum[b]; 42 } 43 } 44 45 int main() 46 { 47 int n; 48 while(scanf("%d",&n)!=EOF) 49 { 50 init();//初始化并查集 51 while(n--) 52 { 53 int a,b; 54 scanf("%d%d",&a,&b); 55 merge(a,b); 56 } 57 printf("%d\n",maxn); 58 } 59 }
标签:
原文地址:http://www.cnblogs.com/wsaaaaa/p/4288107.html