首页 > 代码库 > hdu 1325 Is It A Tree?

hdu 1325 Is It A Tree?

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

  1 #include <cstdio>
  2 #include <cstring>
  3 #include <algorithm>
  4 #define maxn 5000
  5 using namespace std;
  6 
  7 int in[maxn],f[maxn];
  8 bool ha[maxn];
  9 int max1;
 10 
 11 struct node
 12 {
 13     int u,v;
 14 }p[maxn*4];
 15 
 16 void inti()
 17 {
 18     for(int i=1; i<=max1; i++)
 19     {
 20         f[i]=i;
 21     }
 22 }
 23 
 24 int find1(int x)
 25 {
 26     if(x==f[x]) return x;
 27     return f[x]=find1(f[x]);
 28 }
 29 
 30 void union1(int a,int b)
 31 {
 32     int fa=find1(a);
 33     int fb=find1(b);
 34     if(fa!=fb)
 35     {
 36         f[fb]=fa;
 37     }
 38 }
 39 
 40 int main()
 41 {
 42     int case1=1;
 43     while(scanf("%d%d",&p[0].u,&p[0].v)!=EOF)
 44     {
 45         if(p[0].u<0||p[0].v<0) break;
 46         if(p[0].u==0&&p[0].v==0)
 47         {
 48             printf("Case %d is a tree.\n",case1++);
 49             continue;
 50         }
 51         memset(in,0,sizeof(in));
 52         memset(ha,false,sizeof(ha));
 53         max1=0;
 54         max1=max(max1,p[0].u);
 55         max1=max(max1,p[0].v); 
 56         ha[p[0].u]=ha[p[0].v]=true;
 57         in[p[0].v]++;
 58         int m=1;
 59         while(scanf("%d%d",&p[m].u,&p[m].v))
 60         {
 61             if(p[m].u==0&&p[m].v==0) break;
 62             in[p[m].v]++;
 63             ha[p[m].u]=ha[p[m].v]=true;
 64             max1=max(max1,p[m].u);
 65             max1=max(max1,p[m].v);
 66             m++;
 67         }
 68         bool flag1=false;
 69         int m1=0;
 70         for(int i=1; i<=max1; i++)
 71         {
 72             if(ha[i]&&in[i]>1)
 73             {
 74                 flag1=true;
 75                 break;
 76             }
 77         }
 78         for(int i=1; i<=max1; i++)
 79         {
 80             if(ha[i]&&in[i]==0) m1++;
 81         }
 82         if(flag1||m1!=1)
 83         {
 84              printf("Case %d is not a tree.\n",case1++);
 85              continue;
 86         }
 87         inti();
 88         for(int i=0; i<m; i++)
 89         {
 90             union1(p[i].u,p[i].v);
 91         }
 92         int ans=0;
 93         for(int i=1; i<=max1; i++)
 94         {
 95             if(ha[i]&&f[i]==i) ans++;
 96         }
 97         if(ans!=1) printf("Case %d is not a tree.\n",case1++);
 98         else
 99             printf("Case %d is a tree.\n",case1++);
100     }
101     return 0;
102 }
View Code