1004 Counting Leaves (30 分)

TIM截图20190305150619.jpg

#include <iostream>
using namespace std;
typedef struct {
	int level;//节点所在层次
	int flag;//0没有孩子,1有孩子
	int father;//父节点
}Node;
int main()
{
	Node node[205];
	int n, m;//n个节点,m个非叶子节点
	int nowNode, nowNodeNumber, childNode;
	int result[205] = { 0 };
	int maxLevel = 1;
	cin >> n >> m;

	//初始化
	for (int i = 0;i <= n; i++) {
		node[i].level = 0;
		node[i].flag = 0;
		node[i].father = 0;
	}
	//编号为1的根节点层号为1
	node[1].level = 1;
	//输入并保存关系
	while (m--) {
		cin >> nowNode;//节点编号
		cin >> nowNodeNumber;//孩子数
		//标记该节点有孩子
		if (nowNodeNumber > 0) {
			node[nowNode].flag = 1;
		}
		for (int j = 0;j < nowNodeNumber;j++) {
			cin >> childNode;
			//保存自己的父亲节点
			node[childNode].father = nowNode;	
		}
	}

	for (int i = 1;i <= n;i++) {
		for (int j = 0;j <= n;j++) {
			if (node[j].father == i) {
				node[j].level = node[i].level + 1;
			}
		}
	}
	for (int i = 1;i <= n;i++) {
		if (node[i].flag == 0) {//叶节点
			result[node[i].level]++;
		}
		//记录下最大的层号
		if (node[i].level > maxLevel) {
			maxLevel = node[i].level;
		}
	}

	for (int i = 1;i < maxLevel;i++) {
		cout << result[i] << " ";
	}
	cout << result[maxLevel];
	return 0;
}

参考博客:http://www.cnblogs.com/linkstar/p/5674895.html

posted @ 2019-03-05 15:08  Chance-Zou  阅读(450)  评论(0编辑  收藏  举报