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 LXY5201314 at 2018-04-22 10:42:21 on Problem 2524
#include<cstdio>
#include<cstring>
int n,m,p[50005],ans;
void ini()
{
    int i;
    for(i=1;i<=n;i++)
        p[i]=i;
}
int find(int x)     //压缩路径
{
    if(p[x]!=x)return p[x]=find(p[x]);
    return p[x];
}
/*int find(int x)       //不压缩路径
{
    while(p[x]!=x)x=p[x];
    return x;
}*/
void combine(int x,int y)
{
    x=find(x);
    y=find(y);
    if(x!=y)
    {
        ans--;
        p[y]=x;
    }
}
int main()
{
    int i,a,b,k=1;
    while(scanf("%d%d",&n,&m)!=EOF)
    {
        if(m==0&&n==0)break;
        ini();
        ans=n;
        for(i=1;i<=m;i++)
        {
            scanf("%d%d",&a,&b);
            combine(a,b);
        }
        printf("Case %d: %d\n",k++,ans);
    }
    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