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
文章大致含义:
第一行有两个数据,一个是总结点数n,一个非叶结点数m,接下来就是对m个非页结点具体信息,01是根节点,然后是儿子结点的个数,接下来才是儿子结点的数字;问题求每一层的没儿子的结点数量。
设置结点结构体,由题意得需要知道层数,还有父亲结点以及是否有儿子结点,这三个属性封装成结构体。
源代码:
- #include<iostream>
- using namespace std;
- struct Node{
- int father;
- int level;
- bool havechild;
- };
- Node node[101];
- int sumnochild[101];
- int main()
- {
- int n,m;
- int nownode_childnum,nownode,childnode;
- int maxlevel=1;
- cin>>n>>m;
- //结构体结点的初始化
- for(int i=0;i<n;i++)
- {
- node[i].father=0;
- node[i].level=0;
- node[i].havechild=0;
- }
- node[1].level=1;
- //因为第一个节点肯定是根节点,所以直接动第二个几点开始算
- for(int i=1;i<=m;i++)
- {
- cin>>nownode;//目前所在结点
- cin>>nownode_childnum;//拥有的儿子数量
- if(nownode_childnum!=0)
- {
- node[nownode].havechild=1;//如果儿子数量不为0,则现在结点的bool变成true即=1
- }
- while(nownode_childnum--)
- {
- cin>>childnode;
- node[childnode].father=nownode;//每一次输入记录父子信息
- }
- }
- //这里其实有点多余了但是为了简单,我就全局遍历了,就是使儿子结点的层数是父亲结点的层数+1
- for(int i=1;i<=n;i++)
- {
- for(int j=1;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].havechild==0 && node[i].level!=0)
- sumnochild[node[i].level]++;
- if(node[i].level>maxlevel)
- maxlevel=node[i].level;
- }
- for (int i=1;i<maxlevel;i++)
- {
- cout<<sumnochild[i]<<" ";
- }
- cout<<sumnochild[maxlevel];
- return 0;
- }