HDU1325---Is It A Tree?

来源:互联网 发布:led显示屏厂商 知乎 编辑:程序博客网 时间:2024/04/27 21:38

和HDU1272非常像。。。

只不过加上了一个箭头啊啊啊,这样子就有方向了。

所以最后一定有一个数是只出不入的,就是他只会指向别人的,否则就有两个树根了,就是NOT了,和1272不同的是多了方向。所以在入度加一个判断。

还有还有。。。负数结束,并不是-1

 

提供几组数据

6 8 5 3 5 2 6 4 5 6 0 0

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

3 8 6 8 6 4 5 3 5 6 5 2 0 0

0 0

1 2 3 4 4 3 0 0

1 2 3 4 0 0

-2 -1

 

第三个第五个第六个NOT,其他都是yes。

#include<stdio.h>#include<string.h>#include<algorithm>#include<map>#include<set>#include<vector>using namespace std;#define MAX 100010map<int,int>mp1;map<int,int>mp2;int pre[MAX],flag,sum[MAX];int find(int x){    int r=x;    while(r!=pre[r])        r=pre[r];    int i=x,j;    while(pre[i]!=r)    {        j=pre[i];        pre[i]=r;;        i=j;    }    return r;}void uni(int a,int b){    int dx=find(a);    int dy=find(b);    if(dx!=dy)    {        pre[dx]=dy;        sum[dy]+=sum[dx];    }    else flag=1;}int main(){    int a,b,temp,cas=1;    while(scanf("%d%d",&a,&b)!=EOF)    {   if(a<0||b<0) break;        mp1.clear();        mp2.clear();        for(int i=1;i<=100010;i++)            pre[i]=i,sum[i]=1;        flag=0;        int num=0;        if(a==0&&b==0) {printf("Case %d is a tree.\n",cas++);continue;}        else         {temp=a;            if(mp1[a]==0) {mp1[a]++;num++;}          if(mp1[b]==0) {mp1[b]++;num++;}          if(mp2[b]==0) mp2[b]++;          uni(a,b);         }         //printf("%d %d \n",find(a),find(b));        while(scanf("%d%d",&a,&b))        {         if(a==0&&b==0) break;         else         {if(mp1[a]==0) {mp1[a]++;num++;}          if(mp1[b]==0) {mp1[b]++;num++;}          if(mp2[b]==0) mp2[b]++;          uni(a,b);         }        }        int b=find(temp);     //   printf("%d sum=%d\n",temp,sum[b]);        if(sum[b]!=mp1.size())            flag=1;        int sm=0;        int t1=mp1.size(),t2=mp2.size();        //printf("%d %d\n",t1,t2);        if(t1-t2!=1)            flag=1;        if(flag==1)            printf("Case %d is not a tree.\n",cas++);        else printf("Case %d is a tree.\n",cas++);    }    return 0;}


 

 

0 0
原创粉丝点击