hdu 1856 More is better (并查集)
水题。离散化,然后求最大集合元素个数。
忘记压缩路径了,tle了很久。- -
代码如下:
1 #include <cstdio> 2 #include <cstring> 3 #include <iostream> 4 #include <algorithm> 5 #include <map> 6 7 using namespace std; 8 9 const int N = 222222; 10 map<int, int> id; 11 12 struct MFS { 13 int fa[N], sz[N], mxsz; 14 void init() { 15 for (int i = 0; i < N; i++) fa[i] = i, sz[i] = 1; 16 mxsz = 1; 17 } 18 int find(int x) { return fa[x] = x == fa[x] ? x : find(fa[x]);} 19 void merge(int x, int y) { 20 int fx = find(x), fy = find(y); 21 if (fx == fy) return ; 22 fa[fx] = fy; 23 sz[fy] += sz[fx]; 24 mxsz = max(mxsz, sz[fy]); 25 } 26 } mfs; 27 28 int main() { 29 int n, x, y; 30 while (~scanf("%d", &n)) { 31 mfs.init(); 32 id.clear(); 33 while (n--) { 34 scanf("%d%d", &x, &y); 35 if (id.find(x) == id.end()) id[x] = id.size(); 36 if (id.find(y) == id.end()) id[y] = id.size(); 37 mfs.merge(id[x], id[y]); 38 } 39 printf("%d\n", mfs.mxsz); 40 } 41 return 0; 42 }
1 #include <cstdio> 2 #include <iostream> 3 #include <algorithm> 4 #include <cstring> 5 6 using namespace std; 7 8 const int N = 222222; 9 const int M = 11111111; 10 11 struct MFS { 12 int fa[N], sz[N], mxsz; 13 void init() { mxsz = 1;} 14 int find(int x) { return fa[x] = fa[x] == x ? x : find(fa[x]);} 15 void merge(int x, int y) { 16 int fx = find(x); 17 int fy = find(y); 18 if (fx == fy) return ; 19 if (sz[fx] > sz[fy]) { 20 fa[fx] = fy; 21 sz[fy] += sz[fx]; 22 mxsz = max(mxsz, sz[fy]); 23 } else { 24 fa[fy] = fx; 25 sz[fx] += sz[fy]; 26 mxsz = max(mxsz, sz[fx]); 27 } 28 } 29 } mfs; 30 31 inline bool isdg(char x) { return '0' <= x && x <= '9';} 32 void scan(int &x) { 33 char ch; 34 while (!isdg(ch = getchar())) ; 35 x = ch - '0'; 36 while (isdg(ch = getchar())) x = x * 10 + ch - '0'; 37 } 38 39 int id[M], rx[N], x[N >> 1], y[N >> 1]; 40 41 int main() { 42 int n; 43 while (~scanf("%d", &n)) { 44 mfs.init(); 45 for (int i = 0; i < n; i++) { 46 //scanf("%d%d", &x[i], &y[i]); 47 scan(x[i]), scan(y[i]); 48 rx[i << 1] = x[i]; 49 rx[i << 1 | 1] = y[i]; 50 } 51 sort(rx, rx + (n << 1)); 52 int m = unique(rx, rx + (n << 1)) - rx; 53 for (int i = 0; i < m; i++) id[rx[i]] = i, mfs.sz[i] = 1, mfs.fa[i] = i; 54 for (int i = 0; i < n; i++) { 55 mfs.merge(id[x[i]], id[y[i]]); 56 } 57 printf("%d\n", mfs.mxsz); 58 } 59 return 0; 60 }
——written by Lyon