Online JudgeProblem SetAuthorsOnline ContestsUser
Web Board
Home Page
F.A.Qs
Statistical Charts
Problems
Submit Problem
Online Status
Prob.ID:
Register
Update your info
Authors ranklist
Current Contest
Past Contests
Scheduled Contests
Award Contest
User ID:
Password:
  Register

自己第一个并查集的题目,小庆贺一下

Posted by oath at 2008-07-20 14:30:23 on Problem 2524
贴一下自己的代码,仅供参考

#include<stdio.h>

long int sum;
long int num[50001],father[50001],i,j;

void makeset(int n)
{
    for(i=0;i<n;i++)
    father[i]=-1;
    num[i]=1;        
}

long int find(int x)
{
    long int r=x,q;
    while(father[r]!=-1)
    r=father[r];
    while(x!=r)
    {
       q=father[x];
       father[x]=r;
       x=q;
    }
    return r;
}

void unionset(int a,int b)
{
     if(a==b)return;
     if(num[a]>num[b])
        father[b]=a;
     else father[a]=b;
     if(num[a]==num[b])
     num[b]++;
     sum--;
}


int main()
{
    long int n,m,a,b;
    long int count=1;
    while(scanf("%d%d",&n,&m))
    {
       if(n==0&&m==0)break;
       sum=n;
       makeset(n);
       for(i=0;i<m;i++)
       {
          scanf("%d",&a);
          scanf("%d",&b);
          a=find(a);
          b=find(b);
          unionset(a,b);
       }
       printf("%s%d%s%d\n","Case ",count,": ",sum);
       count++;
    }
    return 0;
}

Followed by:

Post your reply here:
User ID:
Password:
Title:

Content:

Home Page   Go Back  To top


All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator