zoukankan      html  css  js  c++  java
  • HDOJ1272(并查集,判断是否为树)

    0 0 Yes

    1 1 0 0 Yes

    1 2 2 1 0 0 No

    //自回路不算一条边的! 居然有 0 0 这样的测试数据

    #include<iostream>
    #include<cstdio>
    #include<cstring>
    #include<set>
    using namespace std;
    set<int> ans;
    set<int> member;
    const int SIZE=100000+16;
    int par[SIZE];
    int rnk[SIZE];
    void init(int n)
    {
        for(int i=0; i<=n; i++)
        {
            par[i]=i;
            rnk[i]=0;
        }
    }
    
    int fnd(int x)
    {
        if(par[x]==x)
            return x;
        return par[x]=fnd(par[x]);
    }
    
    void unite(int x, int y)
    {
        int a=fnd(x);
        int b=fnd(y);
        
        if(a==b)
            return ;
        if(rnk[a]<rnk[b])
        {
            par[a]=b;
        }
        else
        {
            par[b]=a;
            if(rnk[a]==rnk[b])
                rnk[a]++;
        }
    }
    
    int main()
    {
        
        int x,y;
        int cnt=0;
        init(SIZE-1);
        int flag=0;
        while(scanf("%d %d",&x, &y)!=EOF&&x!=-1&&y!=-1)
        {
            if(x==0&&y==0)
            {
                if(flag==0)
                {
                    printf("Yes
    ");
                    continue;
                }
                
                if(member.size()!=cnt+1)
                {
                    printf("No
    ");
                }
                else
                {
            
                    for(set<int>:: iterator it=member.begin(); it!=member.end(); it++)
                    {
                        ans.insert(fnd(*it));
                    }
                    if(ans.size()==1)
                        printf("Yes
    ");
                    else
                        printf("No
    ");
                }
                
                member.clear();
                ans.clear();
                cnt=0;
                init(SIZE-1);
                flag=0;
            }
            else
            {
                flag=1;
                unite(x,y);
                member.insert(x);
                member.insert(y);
                if(x!=y)
                {
                    cnt++;
                }
            }
            
        }
        
        return 0;
    }
  • 相关阅读:
    socket
    netstat
    列表
    突然发现不会写代码了
    算法资源
    bit位操作
    排序算法
    连续子数组最大和
    books
    凸优化
  • 原文地址:https://www.cnblogs.com/program-ccc/p/4707162.html
Copyright © 2011-2022 走看看