您的位置:首页 > 其它

poj 1308 Is It A Tree?

2017-08-13 21:05 429 查看
题目:





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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: