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
题意:给你一个家族树,让你求每一层上叶子结点的个数。
思路:两次bfs,第一次bfs把所有点标记为在第几层上,第二个bfs判断他是否有子节点。利用邻接表,if(he[top]==0) 说明没有子节点,sum[ num[top] ]++。 sum[i]代表第i层有多少个叶子结点,num[top]代表top在第几层。
邻接表:
ll add(ll x,ll y,ll z)
{
ver[id]=y;//x点的终边
len[id]=z;// x->y的权值
ne[id]=he[x];//下一个节点
he[x]=id++;//头结点
}
满分代码:
#include<iostream>
#include<queue>
using namespace std;
typedef long long ll;
const int maxn=1e3+10;
ll num[maxn],sum[maxn],he[maxn],ne[maxn],ver[maxn];
ll id,top;
queue<ll> q1,q2;
void init()
{
for(int i=0;i<maxn;i++)
{
num[i]=0;
sum[i]=0;
he[i]=0;
ne[i]=0;
ver[i]=0;
}
}
ll bfs1(ll u)
{
q1.push(u);
num[u]=1;
while(!q1.empty())
{
top=q1.front();
q1.pop();
for(int i=he[top];i;i=ne[i])
{
ll e=ver[i];
num[e]=num[top]+1;
q1.push(e);
}
}
}
ll bfs2(ll u)
{
q2.push(u);
while(!q2.empty())
{
top=q2.front();
q2.pop();
if(he[top]==0)
sum[num[top]]++;
else
{
for(int i=he[top];i;i=ne[i])
{
ll oo=ver[i];
q2.push(oo);
}
}
}
}
ll add(ll x,ll y)
{
ver[id]=y;
ne[id]=he[x];
he[x]=id++;
}
int main()
{
ll n,m;
while(cin>>n)
{
init();
cin>>m;
id=1;
for(int i=1;i<=m;i++)
{
ll root,k,a;
cin>>root>>k;
for(int i=1;i<=k;i++)
{
cin>>a;
add(root,a);
}
}
bfs1(1);
ll m1=0;
for(int i=1;i<=n;i++)
{
m1=max(m1,num[i]);
}
bfs2(1);
for(int i=1;i<=m1;i++)
{
cout<<sum[i];
if(i<m1)
cout<<" ";
}
cout<<endl;
}
return 0;
}