HDU 1325 Is It A Tree?

题意

判断一系列的输入是否是一棵树

思路

比HDU 1272多判断一个入度,如果入度为0的点不止一个,就肯定不是一颗树

传送门

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

Code

#include 
#include 
#include 

using namespace std;

class UnionFind {
private:
    int * fa;
    int size;
public: 
    UnionFind(int n) {
        size = n;
        fa = new int[n+1];
        Init();
    }

    ~UnionFind() {
        delete[] fa;
    }

    void Init() {
        for(int i = 1 ; i <= size ; i ++) {
            fa[i] = i;
        }
    }

    int Find(int x) {
        if(fa[x] != x) {
            fa[x] = Find(fa[x]);
        }
        return fa[x];
    }

    bool Union(int x,int y) {
        int fx = Find(x);
        int fy = Find(y);
        if(fx != fy) {
            fa[fx] = fy;
            return true;
        }
        else {
            return false;
        }
    }

    int GetCount() {
        int count = 0;
        for(int i = 1 ; i <= size ; i ++) {
            if(fa[i] == i) {
                count ++;
            }
        }
        return count;
    }
};

#define MAXN 1000005

bool vis[MAXN+1];
int indegree[MAXN+1];

int main() {
    int u,v;
    int cnt = 0;
    UnionFind uf(MAXN);
    memset(vis,0,sizeof(vis));
    bool haveCircle = false;
    int indegreeZeroNum = 0;

    while(~scanf("%d %d",&u,&v)) {
        if(u < 0 && v < 0) {
            break;
        }
        if(u == 0 && v == 0) {
            int tmpcnt = 0;
            for(int i = 1 ; i <= MAXN ; i++) {
                if(vis[i]) {
                    tmpcnt ++;
                    if(indegree[i] == 0) {
                        // printf("%d\n", i);
                        indegreeZeroNum ++;
                    }
                } 
            }
            // printf("%d\n", indegreeZeroNum);
            if(indegreeZeroNum == 1 && haveCircle == false && uf.GetCount() + tmpcnt == MAXN + 1) {
                printf("Case %d is a tree.\n",++cnt);
            }
            else {
                printf("Case %d is not a tree.\n",++cnt);
            }
            uf.Init();
            memset(vis,0,sizeof(vis));
            memset(indegree,0,sizeof(indegree));
            indegreeZeroNum = 0;
            haveCircle = false;
        }
        else {
            vis[u] = true;
            vis[v] = true;
            indegree[v] ++;
            if(false == uf.Union(u,v)) {
                haveCircle = true;
            }
        }
    }
    return 0;
}

你可能感兴趣的:(图论500题)