Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 18778 | Accepted: 6395 |
Description
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.
Input
Output
Sample Input
6 8 5 3 5 2 6 4
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
Sample Output
Case 1 is a tree.
Case 2 is a tree.
Case 3 is not a tree.
题目大意:给出一些数字对,代表父节点和子节点,输入以0 0结束,问这些节点能否构成一棵树。
解题方法:判断能否构成一棵树的条件:1.空树是一棵树。2.树中不存在回路。3.森林不是树。可以用并查集判断是否存在回路,然后用并查集扫描一遍,看是否所有节点的最顶端父节点相同,不同则为森林。
#include <stdio.h>
#include <iostream>
#include <string.h>
using namespace std; typedef struct
{
int rank;
int parent;
}UFSTree; UFSTree Set[];
int Stack[];//用于保存每个节点对中的父节点,以检测是否为森林 void MakeSet()
{
for (int i = ; i < ; i++)
{
Set[i].rank = ;
Set[i].parent = i;
}
} int FindSet(int x)
{
if (x == Set[x].parent)
{
return x;
}
else
{
return FindSet(Set[x].parent);
}
} void UnionSet(int x, int y)
{
x = FindSet(x);
y = FindSet(y);
if (Set[x].rank > Set[y].rank)
{
Set[y].parent = x;
}
else
{
Set[x].parent = y;
if (Set[x].rank == Set[y].rank)
{
Set[y].rank++;
}
}
} int main()
{
int x, y, nCase = , top = ;
bool flag = true;
MakeSet();
while(scanf("%d%d", &x, &y) != NULL && x != - && y != -)
{
while()
{
if (x == && y == )
{
break;
}
Stack[top] = x;
top++;
//如果两个节点处于同一集合,则不能形成一棵树
if (FindSet(x) == FindSet(y))
{
flag = false;
}
else
{
UnionSet(x, y);
}
scanf("%d%d", &x, &y);
}
if (flag)
{
//查询每个节点对中的父节点,看所有节点的最顶端父节点是否相同,不相同则为森林
for (int i = ; i < top - ; i++)
{
int n1 = FindSet(Stack[i]);
int n2 = FindSet(Stack[i + ]);
if (n1 != n2)
{
flag = false;
break;
}
}
}
if (flag)
{
flag = true;
printf("Case %d is a tree.\n", nCase++);
}
else
{
flag = true;
printf("Case %d is not a tree.\n", nCase++);
}
MakeSet();
top = ;
}
return ;
}