ACM程序设计题,高手答复

来源:百度知道 编辑:UC知道 时间:2024/05/22 17:39:23
(详情请进:http://acm.jlu.edu.cn/joj/showproblem.php?pid=1132
A tree is a well-known data structure that is either empty (null, void, nothing) or is a set of one or more nodes connected by directed edges between nodes satisfying the following properties.
1.There is exactly one node, called the root, to which no directed edges point.

2.Every node except the root has exactly one edge pointing to it.

3.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 sati

我就晕死了,没考虑到这种情况。
2
1 2 1 2
不是棵树。
害我挂了4次~~
我主要思想是:
根据输入建立一个关系链接矩阵。 然后找到无入度的点作为根点,开始深搜遍历,遍历过程中记录遍历过的点,当遍历过程中,如又碰到已经遍历的点,那么说明它肯定不是棵数。。。,因为此时已经存在了不止一条路径从根节点到该节点。
如果上判断通过,就判断是否所有的点被访问到了。。 如果 有,说明他可能是一个森林,至少不是树了。。。
我的 代码如下:

#include <stdio.h>
#include <memory>
#define MAX 50
bool relation[MAX][MAX];
int node_num;
bool pass[MAX];
int flage ;

int index(int num)
{
static int index[MAX];
int i ;
for( i =0 ; i < node_num ; i ++ )
if(num == index[i]) return i;
index[i] = num ;
node_num++;
return i ;
}

int find_root()
{
int i , j ;
for( j =0 ; j < node_num ; j ++ )
{
for( i = 0 ; i < node_num ; i ++ )
if( relation[i][j] != 0 ) break ;
if(i >= node_num ) return j ;
}
return -1 ;
}

void dfs( int node )
{<