Is It A Tree?
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 22720 Accepted Submission(s): 5168
There is exactly one node, called the root, to which no directed edges point.
Every node except the root has exactly one edge pointing to it.
There is a unique sequence of directed edges from the root to each node.
For example, consider the illustrations below, in which nodes are represented by circles and edges are represented by lines with arrowheads. The first two of these are trees, but the last is not.
In this problem you will be given several descriptions of collections of nodes connected by directed edges. For each of these you are to determine if the collection satisfies the definition of a tree or not.
5 6 0 0
8 1 7 3 6 2 8 9 7 5
7 4 7 8 7 6 0 0
3 8 6 8 6 4
5 3 5 6 5 2 0 0
-1 -1
#include <stdio.h>
#include <algorithm>
#include <math.h>
#include <string.h>
using namespace std;
class Union_Find_Set {
#define MAX_UNION_FIND_SET_SIZE 100005
public:
int setSize;
int father[MAX_UNION_FIND_SET_SIZE];
Union_Find_Set() {
setSize = ;
}
Union_Find_Set(int x) {
setSize = x;
clear(x);
}
void clear(int x) {
for (int i = ; i < x; i++) {
father[i] = i;
}
}
int getFather(int x) {
if (x != father[x]) {
father[x] = getFather(father[x]);
}
return father[x];
}
bool merge(int a, int b) {
a = getFather(a);
b = getFather(b);
if (a != b) {
father[a] = b;
return true;
} else {
return false;
}
}
int countRoot() {
int ret = ;
for (int i = ; i < setSize; i++) {
if (father[i] = i) {
ret++;
}
}
return ret;
}
};
Union_Find_Set ufs();
bool v[];
int in[];
int main() {
int a, b, k = , n = , m = ;
bool f = true;
memset(v, false, sizeof(v));
memset(in, , sizeof(in));
while (scanf("%d%d", &a, &b) != EOF) {
if (a == && b == ) {
if (n != m + ) {
f = false;
}
printf("Case %d is %sa tree.\n", ++k, f ? "" : "not ");
ufs.clear();
n = m = ;
memset(v, false, sizeof(v));
memset(in, , sizeof(in));
f = true;
} else if (a < && b < ) {
break;
} else {
m++;
if (!v[a]) {
v[a] = true;
n++;
}
if (!v[b]) {
v[b] = true;
n++;
}
in[b]++;
if (in[b] > ) {
f = false;
}
if (!ufs.merge(b, a)) {
f = false;
}
}
}
return ;
}