POJ1308-Is It A Tree?

http://poj.org/problem?id=1308

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#define maxn 1006
using namespace std;
struct Edge
{
    int v, next;
}edge[1000005];
int name[maxn],in[maxn],head[maxn],vis[maxn],n,ecount,tot,root,ok;
void addedge(int a,int b)
{
    edge[ecount].next=head[a];
    edge[ecount].v=b;
    head[a]=ecount;
    in[b]++;
    ecount++;
}
int find(int a)
{
    for(int i=0;i<n;i++)
       if(name[i]==a)
          return i;
    name[n++]=a;
    return n-1;
}
void dfs(int root)
{
    vis[root]=1;
    tot++;
    for(int i=head[root];i!=-1;i=edge[i].next)
    {
        if(vis[edge[i].v])
        {
            ok=0;
            return;
        }
        if(!ok)
           return;
        dfs(edge[i].v);
    }
}
int main(void)
{
    int a,b,t=0;
    while (1)
    {
        t++;
        memset(in,0,sizeof(in));
        memset(head,-1,sizeof(head));
        memset(vis,0,sizeof(vis));
        ecount=n=tot=0;
        ok = 1;
        scanf("%d%d",&a,&b);
        if(a<0&&b<0)
           return 0;
        if(a==0&&b==0)
        {
            printf("Case %d is a tree.\n",t);
            continue;
        }
        a=find(a);
        b=find(b);
        addedge(a,b);
        while(1)
        {
            scanf("%d%d",&a,&b);
            if(a==0&&b==0)
               break;
            a=find(a);
            b=find(b);
            addedge(a,b);
        }
        root=-1;
        for(int i=0;i<n;i++)
           if(in[i]==0)
              root=i;
        if(root>=0)
           dfs(root);
        if(ok&&tot==n&&root>=0)
           printf("Case %d is a tree.\n",t);
        else
           printf("Case %d is not a tree.\n",t);
    }
    return 0;
}
posted @ 2012-08-30 21:19  Yogurt Shen  阅读(138)  评论(0编辑  收藏  举报