标签:并查集
4 1 2 3 4 5 6 1 6 4 1 2 3 4 5 6 7 8
4 2HintA 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.#include <stdio.h> #include <stdlib.h> #include <malloc.h> #include <limits.h> #include <ctype.h> #include <string.h> #include <string> #include <math.h> #include <algorithm> #include <iostream> #include <deque> #include <vector> #include <stack> #include <queue> #include <set> #include <map> using namespace std; #define MAXN 10000010 int father[MAXN]; int ans[MAXN]; int a[100010],b[100010]; int max1(int a,int b){ return a>b?a:b; } int find(int x){ if(x != father[x]){ father[x] = find(father[x]); } return father[x]; } int main(){ int n,i; while(~scanf("%d",&n)){ if(n == 0){ printf("1\n"); continue; } for(i=1;i<MAXN;i++){ ans[i] = 1; } for(i=1;i<MAXN;i++){ father[i] = i; } for(i=0;i<n;i++){ scanf("%d%d",&a[i],&b[i]); } int sum = -1; for(i=0;i<n;i++){ int f1 = find(a[i]); int f2 = find(b[i]); if(f1 != f2){ if(ans[f1] < ans[f2]){ ans[f2]+=ans[f1]; father[f1] =f2; sum = max1(sum,ans[f2]); } else{ ans[f1]+=ans[f2]; father[f2] = f1; sum = max1(sum,ans[f1]); } } } printf("%d\n",sum); } return 0; }
标签:并查集
原文地址:http://blog.csdn.net/zcr_7/article/details/39896577