HDU1856More is better(并查集)
最近发现以前的东西都忘得差不多了,在这里刷刷水题
并查集:
1 int find_parent(int x) 2 { 3 return x = p[x] ? x : p[x] = find_parent(p[x]); 4 } 5 6 void merg(int a,int b) 7 { 8 int x = find_parent(a); 9 int y = find_parent(b); 10 if(x != y) 11 { 12 p[x] = y; 13 } 14 }
1 #include<iostream> 2 #include<stdio.h> 3 #include<string.h> 4 #include<map> 5 #include<vector> 6 #include<set> 7 #include<stack> 8 #include<queue> 9 #include<algorithm> 10 #include<stdlib.h> 11 using namespace std; 12 #define MAX(a,b) (a > b ? a : b) 13 #define MIN(a,b) (a < b ? a : b) 14 #define MAXN 10000001 15 #define INF 2000000007 16 #define mem(a) memset(a,0,sizeof(a)) 17 18 int p[MAXN]; 19 int ans[MAXN]; 20 21 int find(int x) 22 { 23 return x==p[x]? x : p[x] = find(p[x]); 24 } 25 26 void merg(int a, int b) 27 { 28 int x = find(a); 29 int y = find(b); 30 if(x != y) 31 { 32 p[x] = y; 33 ans[y] +=ans[x]; 34 } 35 } 36 37 int main() 38 { 39 int n; 40 while(~scanf("%d", &n)) 41 { 42 if(n == 0) 43 { 44 printf("1\n"); 45 continue; 46 } 47 int a,b,i; 48 for(i =0;i<= MAXN;i++) 49 { 50 p[i] = i; 51 ans[i] =1; 52 } 53 for(i = 0; i < n ;i++) 54 { 55 scanf("%d%d",&a, &b); 56 merg(a,b); 57 } 58 int max = 0; 59 for(i =0 ;i<=MAXN;i++) 60 { 61 max = MAX(max, ans[i]); 62 } 63 printf("%d\n",max); 64 } 65 return 0; 66 }