C/C++教程

1004 Counting Leaves (30 分)

本文主要是介绍1004 Counting Leaves (30 分),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

1004 Counting Leaves (30 分)

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

Input Specification:

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.

The input ends with N being 0. That case must NOT be processed.

Output Specification:

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
结尾无空行
#include <iostream>
#include <queue>
using namespace std;
struct node{
	int layer;
	int id;
};
int main(){
	int n, m;//total nodes, total none leafe node
	cin>>n>>m;
	vector<int> tree[100];//用来存储非叶子结点的孩子们
	for(int i = 0; i < m; i++){
		int id, k;
		cin>>id>>k;
		while(k--){
			int cid;
			cin>>cid;
			tree[id].push_back(cid);// 
		}
	} 
	
//	 BFS遍历每一层
	vector<int> ans(99, 0);
	queue<node> q;
	q.push(node{0, 1});//因为1是root 且处于第一层 
	int layer = 0;
	while(!q.empty()){
		node top = q.front();
		q.pop();//把当前的队头退出
		layer = max(layer, top.layer);//从队列出来的可能是兄弟节点,所以务必用结构体存储每个结点所处层数,root为0层 
//		cout<<top.id<<" "<<" "<<tree[top.id][0]<<" "<<top.layer<<endl;
		if(tree[top.id].size() == 0){
			ans[top.layer]++;//该层的叶子结点个数加加并退出此次循环 
			continue;
		}//该节点没有孩子 
		for(int i = 0; i < tree[top.id].size(); i++){
			q.push(node{top.layer + 1, tree[top.id][i]});//把该节点的所有孩子压栈 
		} 
	} 
	for(int i = 0; i < layer + 1; i++){
		if(i == 0)
			cout<<ans[0];
		else 
			cout<<" "<<ans[i];
	}
} 

总结

使用node的结构体来存储每个结点所处层数,因为层序遍历会压入兄弟节点,所以每次出队的层数不确定,
然后:
对于在tree中没有孩子的则为叶子结点,在ans中的对应层数中加一,跳过此处循环
对于有孩子的则将孩子一一入队,同时注意层数加一

当你要用vector创建二维数组时,使用vector<vector> ans(m); 然后通过push_back方式遍历每层,之后不能直接通过下标取出, ans[i][j]是错的,因为对于第二维你没有初始化大小,无法通过下标取出 只能通过vector ans[100]的方式才能通过下标取出

这篇关于1004 Counting Leaves (30 分)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!