一、题目描述
二、算法分析说明与代码编写指导
取树的充分必要条件【4】即可完成判断。
嗯,这题被放在邝斌专题的并查集里面了,但是用并查集写一直 WA,算了,换种方法。
三、AC 代码
vm:最大的顶点编号
nvi:孤立点的数量
ne:边的数量
id:入度
od:出度
POJ 1308:
#include<cstdio>
#include<algorithm>
#include<bitset>
#pragma warning(disable:4996)
using namespace std;
const unsigned nmax = 200005;
unsigned id[nmax], od[nmax], u, v, vm, t, nvi, ne; bitset<nmax> vis;
int main() {
for (;;) {
vis.reset(); fill(id + 1, id + vm + 1, 0); fill(od + 1, od + vm + 1, 0); nvi = ne = vm = 0;
scanf("%u%u", &u, &v);
if (u == -1)return 0;
else if (u == 0) { printf("Case %u is a tree.\n", ++t); continue; }
++od[u]; ++id[v]; vm = max(vm, max(u, v)); ++ne; vis[u] = vis[v] = true;
for (;;) {
scanf("%u%u", &u, &v); if (u == 0)break;
++od[u]; ++id[v]; vm = max(vm, max(u, v)); ++ne; vis[u] = vis[v] = true;
}
for (unsigned i = 1; i <= vm; ++i) { if (vis[i] == true && id[i] == 0 && od[i] == 0)++nvi; }
printf("Case %u is ", ++t);
if (vis.count() - ne == 1 && nvi == 0)puts("a tree.");
else puts("not a tree.");
}
}
HDU 1272:
#include<cstdio>
#include<algorithm>
#include<bitset>
#pragma warning(disable:4996)
using namespace std;
const unsigned nmax = 200005;
unsigned id[nmax], od[nmax], u, v, vm, nvi, ne; bitset<nmax> vis;
int main() {
for (;;) {
vis.reset(); fill(id + 1, id + vm + 1, 0); fill(od + 1, od + vm + 1, 0); nvi = ne = vm = 0;
scanf("%u%u", &u, &v);
if (u == -1)return 0;
else if (u == 0) { puts("Yes"); continue; }
++od[u]; ++id[v]; vm = max(vm, max(u, v)); ++ne; vis[u] = vis[v] = true;
for (;;) {
scanf("%u%u", &u, &v); if (u == 0)break;
++od[u]; ++id[v]; vm = max(vm, max(u, v)); ++ne; vis[u] = vis[v] = true;
}
for (unsigned i = 1; i <= vm; ++i) { if (vis[i] == true && id[i] == 0 && od[i] == 0)++nvi; }
if (vis.count() - ne == 1 && nvi == 0)puts("Yes");
else puts("No");
}
}