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;
}


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