hdu 1325 判断有向图是否为树

题意:判断有向图是否为树

链接:点我

 

这题用并查集判断连通,连通后有且仅有1个入度为0,其余入度为1,就是树了

 1 #include<cstdio>
 2 #include<iostream>
 3 #include<algorithm>
 4 #include<cstring>
 5 #include<cmath>
 6 #include<queue>
 7 #include<map>
 8 using namespace std;
 9 #define MOD 1000000007
10 const int INF=0x3f3f3f3f;
11 const double eps=1e-5;
12 #define cl(a) memset(a,0,sizeof(a))
13 #define ts printf("*****\n");
14 const int MAXN=1000000;
15 int n,m,tt;
16 int a[MAXN];
17 int f[MAXN];
18 int in[MAXN];
19 bool vis[MAXN];
20 int find(int x)
21 {
22     if(f[x]==-1)    return x;
23     else return f[x]=find(f[x]);
24 }
25 void bing(int x,int y)
26 {
27     int t1=find(x);
28     int t2=find(y);
29     if(t1!=t2)
30         f[t1]=t2;
31 }
32 int main()
33 {
34     int i,j,k;
35     #ifndef ONLINE_JUDGE
36     freopen("1.in","r",stdin);
37     #endif
38     int cnt=0;
39     int u,v;
40     int iCase=0;
41     bool flag=true;
42     memset(f,-1,sizeof(f));
43     memset(vis,false,sizeof(vis));
44     memset(in,0,sizeof(in));
45     while(scanf("%d%d",&u,&v)!=EOF)
46     {
47         if(u==-1&&v==-1)    break;
48         if(u==0&&v==0)
49         {
50             iCase++;
51             printf("Case %d ",iCase);
52             int t0=0;
53             for(i=0;i<cnt;i++)
54             {
55                 if(find(a[i])!=find(a[0]))
56                 {
57                     flag=0;
58                     break;
59                 }
60                 if(in[a[i]]==0) t0++;
61                 else if(in[a[i]]>1)
62                 {
63                     flag=0;
64                     break;
65                 }
66             }
67             if(t0!=1)flag=false;
68             if(cnt==0)flag=true;
69             if(flag)printf("is a tree.\n");
70             else printf("is not a tree.\n");
71             cnt=0;
72             memset(f,-1,sizeof(f));
73             memset(vis,false,sizeof(vis));
74             memset(in,0,sizeof(in));
75             flag=true;
76         }
77         else
78         {
79             if(!vis[u])
80             {
81                 vis[u]=1;
82                 a[cnt++]=u;
83             }
84             if(!vis[v])
85             {
86                 vis[v]=1;
87                 a[cnt++]=v;
88             }
89             if(find(u)==find(v))    flag=0;
90             else
91             {
92                 bing(u,v);
93                 in[v]++;
94             }
95         }
96     }
97 }

 

posted @ 2015-05-03 11:31  miao_a_miao  阅读(536)  评论(0编辑  收藏  举报