pat1004 Counting Leaves

A family hierarchy is usually presented by a pedigree tree. Your job is to count those family members who have no child.

Input

Each input file contains one test case. Each case starts with a line containing 0 < N < 100, the number of nodes in a tree, and M (< N), the number of non-leaf nodes. Then M lines follow, each in the format:

ID K ID[1] ID[2] ... ID[K]
where ID is a two-digit number representing a given non-leaf node, K is the number of its children, followed by a sequence of two-digit ID's of its children. For the sake of simplicity, let us fix the root ID to be 01.

Output

For each test case, you are supposed to count those family members who have no child for every seniority level starting from the root. The numbers must be printed in a line, separated by a space, and there must be no extra space at the end of each line.

The sample case represents a tree with only 2 nodes, where 01 is the root and 02 is its only child. Hence on the root 01 level, there is 0 leaf node; and on the next level, there is 1 leaf node. Then we should output "0 1" in a line.

Sample Input
2 1
01 1 02
Sample Output
0 1

题意:

一个树,输入:结点数N, 非叶子结点数M

其余M行分别输入,结点ID  孩子数K 以及每个孩子的编号

方便起见,令跟ID为1

输出:每一层的叶子个数


思路:叶子即没有孩子,因此,只需要求没有孩子的结点个数,难点是,怎么求这个点在哪一层

            可以通过保存结点的父亲,再回溯求得层数,也可以通过用“邻接表法”, 存放孩子,再深搜

下面的代码是保存父亲ID的写法

#include<stdio.h>
typedef struct{
	int level;
	int child;
	int parent;
	int state;
}node;
node a[105];
int ans[105];
int N, M;

int find_path(int parent, int level){

	if(parent == 1)
		return level;
	else{
		find_path(a[parent].parent , level + 1);
	}
}

int main()
{
	int ID, IDc, child, i, j, level = 1;
	scanf("%d%d", &N, &M);
	for(i = 0; i < 105; i++){//init
		a[i].level  = 0;
		a[i].child = 0;
		a[i].parent = -1;
		a[i].state = 0;
	}
	if(M == 0)//特殊情况,假如,没有非叶子结点,就说明只有1层,且跟结点是叶子
		printf("1\n");
	else{

		while(M--){
			scanf("%d%d", &ID, &child);
			a[ID].state = 1;//结点状态为存在
			a[ID].child = child;//ID的孩子数
			if(ID == 1)
				a[ID].level = 1;
			while(child--){
				scanf("%d", &IDc);
				a[IDc].parent = ID;
				a[IDc].state = 1;
			}
		}

		for(i = 2; i < 101; i++){
			if(a[i].state){
				a[i].level = find_path(a[i].parent, 2);
			}
			level = level > a[i].level ? level : a[i].level;//统计这棵树的层数
		}
		for(i = 1; i < 101; i++)//统计每层的叶子数
			if(a[i].state && a[i].child == 0){
				ans[a[i].level]++;//该层叶子数加1
			}
		for(i = 1; i < level; i++)
			printf("%d ", ans[i]);
		printf("%d", ans[i]);
	}
	return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章