-
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行介绍这m个非叶节点的id,孩子数,以及孩子分别是谁。
思路:,用root[i]表示编号为i的节点的根结点。(可以寻找编号为i的节点所在第几层)。
用level[i]表示编号为i的节点在第几层。
用vis[i]表示编号为i的节点是不是叶子节点。
用num[i]表示第i层有多少个叶子节点。
#include<bits/stdc++.h>
using namespace std;
const int N=110;
int root[N],level[N],num[N],vis[N];
int findxlevel(int x)//寻找编号为x的节点在第几层
{
int co=0;
while(root[x]!=x)
{
co++;
x=root[x];
}
return co;
}
/*
例如,1有2,3两个孩子,2有4,5两个孩子。
root[2]=1,root[3]=1;
root[4]=2,root[5]=2;
4进入findxlevel函数之后,
root[4]=2,co++;x=2;
root[2]=1;co++;x=1;
root[1]=1; return co;
则4在第二层(根节点1在第0层)
*/
int main()
{
int n,m,x,k,id,i;
cin>>n>>m;
for(i=1; i<=n; i++)
{
root[i]=i;
}
memset(vis,0,sizeof(vis));
while(m--)//前m个节点都是非叶节点,vis标记为1
{
cin>>id;
vis[id]=1;
cin>>k;
while(k--)
{
cin>>x;
root[x]=id;
}
}
memset(num,0,sizeof(num));
int maxn=0;
for(i=1; i<=n; i++)
{
level[i]=findxlevel(i);
maxn=max(maxn,level[i]);
if(!vis[i])
num[level[i]]++;
}
for(i=0; i<=maxn; i++)//根节点时会出来在第0层
{
if(i==maxn)
printf("%d\n",num[i]);
else
printf("%d ",num[i]);
}
return 0;
}