并查集 HDU 1856

#include <iostream>

using namespace std;



const int MAXN = 10000005;



struct Node 

{

int parent;//保存父节点

int rank;//以此小男孩为父节点的人数

};

Node boy[MAXN];



void init(void)

{

int i;

for (i = 0; i < MAXN; i++)

{

   boy[i].parent = i;

   boy[i].rank = 1;

}

}



int find(int a)

{

int t;

t = boy[a].parent;

if (t != a)

{

   boy[a].parent = find(t);

}

return boy[a].parent;

}



void Union(int a, int b)

{

int fa, fb;

fa = find(a);

fb = find(b);

if (fa != fb)

{

   boy[fa].parent = fb;

   boy[fb].rank += boy[fa].rank;

}

}



int Count()

{

int i;

int cnt = 0;

for (i = 0; i < MAXN; i++)

{

   if (boy[i].parent == i)

   {

    if (boy[i].rank > cnt)

     cnt = boy[i].rank;

   }

}

return cnt;

}



int main(void)

{

int tcase;

int a, b;



while (scanf("%d", &tcase) != EOF)

{

   init();

   while (tcase--)

   {

    scanf("%d%d", &a, &b);

    Union(a, b);

   }

   printf("%d\n", Count());

}



return 0;

}

你可能感兴趣的:(HDU)