• 【并查集】HDU 1325 Is It A Tree?


    推断是否为树 

    森林不是树

    空树也是树

    成环不是树

    数据:

    1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 1 0 0  

    1 2 2 3 4 5 0 0  

    2 5 0 0 

    ans:

    no

    no

    yes  

    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    #include <limits.h>
    #include <malloc.h>
    #include <ctype.h>
    #include <math.h>
    #include <string>
    #include <iostream>
    #include <algorithm>
    #include <vector>
    #include <string>
    using namespace std;
    typedef long long LL;
    const int maxn =10000+5;
    const int maxe = 15000+5;
    const int INF = 460002326;
    const int mod = 1000000009;//q[i]表示点i 相应的点 rank[i]表示入度
    int fa[maxn],q[maxn],rank[maxn],taj,flag;//taj表示当前点的编号个数
    void init()
    {
        flag=0;
        taj=1;
        for(int i=0; i<maxn; i++)
            fa[i]=i,q[i]=-1,rank[i]=0;
    }
    int find(int x)
    {
        if(fa[x]==x)
            return x;
        else
        {
            fa[x]=find(fa[x]);
            return fa[x];
        }
    }
    void merge(int x,int y)
    {
        int fx=find(x),fy=find(y);
        if(fx==fy)
        {
            flag=1;//反复
            return ;
        }
        else
        {
            fa[fy]=fx;
            rank[y]++;//入度+1
            return ;
        }
    }
    void dian(int a,int b)
    {
        if(q[a]==-1)
            q[a]=taj++;
        if(q[b]==-1)
            q[b]=taj++;
    }
    int main()
    {
        int a,b,cas=0;
        //   freopen("in.txt","r",stdin);
        while(scanf("%d%d",&a,&b),a+b>=0)
        {
            init();//初始化
            if(a==0&&b==0)// 0 0 也算树
            {
                printf("Case %d is a tree.
    ",++cas);
                continue;
            }
            a=q[a],b=q[b];
            merge(a,b);
            while(scanf("%d%d",&a,&b))
            {
                if(a+b==0) break;
                dian(a,b);
                a=q[a],b=q[b];
                merge(a,b);
            }
            a=0;
            for(int i=1; i<maxn; i++)
                find(i);
            for(int i=1; i<maxn; i++)
            {
                if(q[i]!=-1&&fa[q[i]]==q[i])//根节点
                    a++;
                if(rank[i]>1)
                    flag=1;
            }
            printf("Case %d is ",++cas);
            if(a==1&&flag==0&&taj>2)
                puts("a tree.");
            else puts("not a tree.");
        }
        return 0;
    }
    


  • 相关阅读:
    IE11浏览器:请不要再叫我IE,谢谢
    Hadoop HA高可用搭建流程
    YARN
    MapReduce
    HDFS
    shell
    shell总结
    linux总结
    maven+log4j
    Spring
  • 原文地址:https://www.cnblogs.com/zsychanpin/p/6772736.html
Copyright © 2020-2023  润新知