More is better(并查集)

 

#include<stdio.h>
#include<string.h>
const int MAXN=10000010;
int father[MAXN],hash[MAXN];

void Make_set()
{
    for(int i=0;i<MAXN;i++)
    {
        father[i]=i;
        //rank[i]=0;
    }
}

int Find(int x)
{
    int r=x;
    while(r!=father[r])
    {
        r=father[r];
    }
    if(r!=x) father[x]=r;
    return father[x];
}

void Union(int x,int y)
{
    if(x==y) return ;
   /* if(rank[x]>rank[y]) father[y]=x;
    else
    {
        if(rank[x]==rank[y])
        {
            rank[y]++;
        }
        father[x]=y;
    }*/
    father[x]=y;
}

int main()
{
    int T,i,n,a,b;
    while(scanf("%d",&n)!=EOF)
    {
        memset(hash,0,sizeof(hash));
        Make_set();
        for(i=0;i<n;i++)
        {
            scanf("%d%d",&a,&b);
            int x=Find(a);
            int y=Find(b);
            Union(x,y);
        }
        int mx=0;
        for(i=1;i<MAXN;i++)
        {
            hash[Find(father[i])]++;
        }
        for(i=1;i<MAXN;i++)
        {
            if(mx<hash[i]) mx=hash[i];
        }
        printf("%d\n",mx);
    }
    return 0;
}
#include <iostream>
using namespace std;
const int maxn=10000010;
int    n;
struct NODE
{
    int root;
    int num;
}nod[maxn];

struct SEG
{
    int u, v;
}seg[100001];

int u, v;
int maxsum;

int getfather(int r)
{
    if(nod[r].root==-1)
    return r;
    int temp = nod[r].root;
    nod[r].root=getfather(temp);
    return nod[r].root;
}

void union_set(int r1, int r2)
{
    int root1=getfather(r1);
    int root2=getfather(r2);
    nod[root1].root=root2;
    nod[root2].num += nod[root1].num;
    if(nod[root2].num>maxsum)
    {
        maxsum=nod[root2].num;
    }
}
int main()
{
    while(scanf("%d",&n)!=EOF)
    {
        maxsum=1;
        for (int i=1; i<=n; i++)
        {
              scanf("%d %d",&seg[i].u, &seg[i].v);
              nod[ seg[i].u ].root = -1;
              nod[ seg[i].u ].num=1;
              nod[ seg[i].v ].root =-1;
              nod[ seg[i].v ].num = 1;
        }
        for (int i=1; i<=n; i++)
        {
            if(getfather(seg[i].u)!=getfather(seg[i].v))
            {
                union_set(seg[i].u, seg[i].v);
            }
        }
        printf("%d\n", maxsum);
    }
    return 0;
}
posted @ 2012-08-07 09:12  calmound  阅读(158)  评论(0编辑  收藏  举报