并查集求最大集合中元素数量
#include <cstdio> #include <cstring> #define maxn 10000000 + 5 using namespace std; struct friends { int root; int num; }p[maxn]; void init() { for (int i = 1; i <= maxn; i++) { p[i].root = i; p[i].num = 1; } } int Find(int x) { return p[x].root == x ? x : (p[x].root = Find(p[x].root)); } void Join(int x, int y) { int fx = Find(x), fy = Find(y); if (fx != fy) { p[fx].root = fy; p[fy].num += p[fx].num; //printf("%d %d %d %d ", fx, fy, p[fy].num, p[fx].num); } } int main() { int n, m; while (~scanf("%d", &n)) { if(n == 0) { printf("1 "); continue; } init(); for (int i = 0; i < n; i++) { int temp1, temp2; scanf("%d %d", &temp1, &temp2); Join(temp1, temp2); } int maxnum = 0; for (int i = 1; i <= maxn; i++) //printf("%d ", p[i].num); if (Find(i) == i) { if (p[i].num > maxnum) maxnum = p[i].num; } printf("%d ", maxnum); } return 0; }