poj 1308 Is It A Tree?

来源:互联网 发布:dnf商城cd药算法 编辑:程序博客网 时间:2024/06/04 00:44

题目:
这里写图片描述
这里写图片描述
AC情况:
这里写图片描述
思路:
判断是不是树,主要两种情况:1.树根不止有一个。2.树根到某个结点的路径不唯一。
主要算法是并查集。
代码:

#include<iostream>using namespace std;int parent[101];int flag[101];void init() {    for (int x = 0; x < 101; x++) {        parent[x] = x;        flag[x] = 0;    }}int find(int x) {    if (parent[x] != x) parent[x] = find(parent[x]);    return parent[x];}int main() {    int a, b,c=0,f,i,ctr;    while (scanf_s("%d %d",&a,&b)) {        if (a == -1 && b == -1) break;        if (a == 0 && b == 0) {                       //空树也算树            printf("Case %d is a tree.\n", ++c);            continue;        }        init();        flag[a] = 1;        flag[b] = 1;        f = 1;        ctr = -1;                                    //ctr 记录树根数量,把0也算作树根ctr++        do {            a = find(a);            b = find(b);            if (a == b)f = 0;            else parent[b] = a;            scanf_s("%d %d", &a, &b);            flag[a] = 1;            flag[b] = 1;        } while (a != 0 && b != 0);        if (f) {            for (i = 0; i < 101; i++)                if (flag[i] && parent[i] == i)ctr++;            if (ctr == 1)printf("Case %d is a tree.\n", ++c);            else printf("Case %d is not a tree.\n", ++c);        }        else printf("Case %d is not a tree.\n", ++c);    }    return 0;}