Step5.1.2Hud 1325
Is It A Tree?
ProblemDescription
A tree is awell-known data structure that is either empty (null, void, nothing) or is aset of one or more nodes connected by directed edges between nodes satisfyingthe following properties.
There is exactlyone node, called the root, to which no directed edges point.
Every node exceptthe root has exactly one edge pointing to it.
There is a uniquesequence of directed edges from the root to each node.
For example,consider the illustrations below, in which nodes are represented by circles andedges are represented by lines with arrowheads. The first two of these aretrees, but the last is not.
In this problemyou will be given several descriptions of collections of nodes connected bydirected edges. For each of these you are to determine if the collectionsatisfies the definition of a tree or not.
第一道并查集的题。
题解
就是判断所给的关系是否满足一棵树的要求,即每一个结点只有一个父结点,并且两个结点不能够相互为父结点,两个结点在表明有关系前不能再同一棵树里(即祖孙,父子,或一棵树里的远亲关系)。自己不能是自己的父结点,空树也是一棵树。
源代码:
#include <iostream>
#include <string>
#define MAX 100000
using namespace std;
struct node
{
intrank;
intparent;
} tree[MAX];
void init()
{
for(int i = 0;i < MAX;i++)
{
tree[i].parent = i;
tree[i].rank = 0;
}
}
int get_parent(int a)
{
if(a== tree[a].parent)
returna;
else
returnget_parent(tree[a].parent);
}
int main()
{
inta,b;
boolflag = true;
intcount = 1;
init();
while(cin>> a >> b)
{
if(a< 0 && b < 0)
break;
if(!flag&& a && b)
continue;
if(!a&& !b)
{
if(flag)
{
intnum = 0;
for(int i = 1;i < MAX;i++)
{
if(tree[i].rank&& tree[i].parent == i)
num++;
}
if(num> 1)
flag = false;
}
if(flag)
cout << "Case "<< count++ <<" is a tree." << endl;
else
cout << "Case "<< count++ <<" is not a tree." << endl;
init();
flag = true;
continue;
}
else
{
if((a!= b && get_parent(a) == get_parent(b)) || a == b || tree[b].parent !=b)
flag = false;
else
{
tree[b].parent = a;
tree[b].rank = 1;
tree[a].rank = 1;
}
}
}
return0;
}