hdu-1325 Is It A Tree?

http://acm.hdu.edu.cn/showproblem.php?pid=1325

跟小希的迷宫那一题题意差不多,只不过那个是无向图,这个是有向图。那么区别在于这个题在输入边的时候不能指向自身,并且有父亲就不可以接另外的父亲了。

其他的都是一样。

#include<cstdio>
#include<cstring>
#define N 100001
int father[N],mark[N],flag,edges;
int find(int x)
{
    if(x==father[x]) return x;
    father[x]=find(father[x]);
    return father[x];
}

void Union(int x,int y)
{
    int a=find(x);
    int b=find(y);
    if(a==b)
    {
        flag=1;
        return;
    }
    mark[a]=1;
    mark[b]=1;
    edges++;
    father[b]=a;
}
int main()
{
    //freopen("a.txt","r",stdin);
    int a,b,c,d,i,m,cas=1;
    while(1)
    {
        scanf("%d%d",&a,&b);
        if(a<0&&b<0)break;
        if(a==0&&b==0) {printf("Case %d is a tree.\n",cas++);continue;}
        flag=edges=m=0;
        memset(mark,0,sizeof(mark));
        for(i=1;i<=N;i++)
            father[i]=i;
        Union(a,b);
        while(scanf("%d%d",&c,&d)!=EOF)
        {
            if(c==0&&d==0)break;
            if(c==d||father[d]!=d) flag=1;  //注意这里,不能指向自身,只能有一个父亲。
            Union(c,d);
        }
        if(flag) {printf("Case %d is not a tree.\n",cas++);continue;}
        for(i=1;i<=N;i++)
        {
            if(mark[i]) m++;
        }
        //printf("%d %d\n",m,edges);
        if(m==edges+1)
        {
            printf("Case %d is a tree.\n",cas++);
        }
        else printf("Case %d is not a tree.\n",cas++);
    }
    return 0;
}


 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值