poj1308 Is It A Tree

題目鏈接:http://poj.org/problem?id=1308
題意:給你一個有向圖,問你這是不是一棵樹
解析:輸入有點坑,他可能沒有一條邊,其他的你只需要判斷一下邊數是不是等於點數-1,每個結點的前驅結點是不是隻有一個

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
using namespace std;
const int maxn = 1e3+100;
int fa[maxn],vis[maxn];
int main(void)
{
    int x,y,case_t = 1;
    while(~scanf("%d %d",&x,&y))
    {
        if(x==-1 || y==-1)
            break;
        int flag = 1;
        memset(vis,0,sizeof(vis));
        memset(fa,0,sizeof(fa));
        int c1 = 0,c2 = 0;
        if(x!=0)
        {
            do
            {
                if(!fa[y])
                    fa[y] = x;
                else
                    flag = 0;
                if(!vis[x])
                {
                    vis[x] = 1;
                    c1++;
                }
                if(!vis[y])
                {
                    vis[y] = 1;
                    c1++;
                }
                c2++;
            }while(~scanf("%d %d",&x,&y)&&x&&y);
            if(c1-1 != c2)
                flag = 0;
        }
        printf("Case %d ",case_t++);
        if(flag)
            puts("is a tree.");
        else
            puts("is not a tree.");
    }
    return 0;
}
發佈了361 篇原創文章 · 獲贊 28 · 訪問量 17萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章