题目:
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>
#include<algorithm>
using namespace std;
int node[101];//所有100个节点用于记录父节点
int level[101];//记录节点层数
void FindLevel(int i)//用并查集的寻根算法确定层数
{
if (node[i] == -1)
{
level[i] = 1;
}
else if (level[node[i]] != 0)
{
level[i] = 1 + level[node[i]];
}
else
{
FindLevel(node[i]);
level[i] = 1 + level[node[i]];
}
}
int main()
{
int n, m;//总节点数,非叶节点数
cin >> n >> m;//第一行输入
int id,k, kid, max_level = 1;
bool child[101];//记录是否是叶节点
int count[101];//记录第i层叶节点个数
fill(node,node+101,0);
fill(level,level+101,0);
fill(child,child+101,true);//测试点3,4,5
fill(count,count+101,0);//测试点4
node[1] = -1;
for (int i = 0; i < m; i++)//读入每个非叶节点的孩子
{
cin >> id;//读入父节点编号
child[id] = false;//标记非叶节点
cin >> k;//读入孩子个数
for (int j = 0; j < k; j++)//读入他的所有孩子
{
cin >> kid;
node[kid] = id;
}
}
//计算所有节点的层数
for (int i = 1; i <= n; i++)
{
if (level[i] == 0)
{
FindLevel(i);
if (level[i] > max_level)
{
max_level = level[i];//记录最大层数
}
}
}
for (int i = 2; i <= n; i++)
{
if (child[i] == true)//是叶节点
{
count[level[i]]++;//对应层计数
}
}
if (n == 1)
{
cout << "1";
}
else
{
cout << "0";
}//处理第1层输出
for (int i = 2; i <= max_level; i++)
{
cout << " " << count[i];
}//输出其他层
}