您的位置:首页 > 其它

POJ-1308 Is It A Tree? -并查集

2011-05-11 22:27 417 查看
判定是否成环,是否只有一个根,是否为空.

代码如下:

#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <map>
#define MAXN 100000
using namespace std;

int stk[MAXN+5], top, flag;

int set[MAXN+5];

map<int,int>mp;

void init()
{
for (int i = 1; i <= MAXN; ++i) set[i] = i;
top = flag = 0;
mp.clear();
}

int find(int x)
{
return set[x] = x == set[x] ? x : find(set[x]);
}

int main()
{
int x, y, ca = 0;
init();
while (scanf("%d %d", &x, &y), x >= 0 && y >= 0) {
if (!x && !y) {
int k = 0;
for (int i = top; i >= 1; --i) {
if (set[stk[i]] == stk[i]) {
++k;
}
}
if (k == 1 && !flag || top == 0) {
printf("Case %d is a tree.\n", ++ca);
}
else {
printf("Case %d is not a tree.\n", ++ca);
}
init();
}
else {
if (!mp.count(x)) {
mp[x] = 1;
stk[++top] = x;
}
if (!mp.count(y)) {
mp[y] = 1;
stk[++top] = y;
}
int a, b;
a = find(x), b = find(y);
if (a != b) {
set[a] = b;
}
else {
flag = 1;
}
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: