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
30分究極水水水水水題= = 太水了
題目意思:先給你n m兩個數
n代表一共有多少節點,m表示下面多少行
然後下面每一行是這樣的:
爹的ID k個數 兒子1 兒子2 兒子3 … 兒子k
然後讓你求 每一層有多少葉子節點(也就是沒兒子的爹 )
思路很簡單:
標記好父親(pre數組) 標記好兒子(son數組) 然後用queue 層序遍歷每一層
把每一層的葉子節點放進vector中
最後順序輸出好了(真正的送分題 )
這題主要是要記錄每一層要pop多少次,畢竟是多叉樹,哈哈
#include <bits/stdc++.h>
const int maxn=5e5+10;
const int mod=1e9+7;
#define INF 2147483647
#define PI atan(1)*4
#define ll long long
#define CL(a,b) memset(a,b,sizeof(a))
#define pb push_back
#define ss(a) scanf("%s",&a)
#define sc(a) scanf("%d",&a)
#define scc(a,b) scanf("d",&a,&b)
#define sccc(a,b,c) scanf("d%d",&a,&b,&c)
using namespace std;
int pre[105];
int son[105];
queue <int> cen;
vector <int> ans;
int n,m,p,s,a;
int main()
{
while(cin>>n>>m)
{
while(!cen.empty())
cen.pop();
CL(son,0);
for(int i=0;i<=100;i++)
pre[i]=i;
//初始化
while(m--)
{
cin>>s>>p;
for(int i=0;i<p;i++)
{
cin>>a;
pre[a]=s;//a的父親是s
son[s]++;//s這個父親有兒子
}
}
int len=1;//這個表示要pop多少次
cen.push(1);
while(!cen.empty())
{
int flag=0;//這個表示pop到哪裏了
int tt=0;
while(len>flag)
{
int now=cen.front();//記錄當前隊列頭
flag++;
for(int i=1;i<=n;i++)
if(i!=now && pre[i]==now)
cen.push(i);
if(!son[now])tt++;
cen.pop();
}
len=cen.size();//記錄這層的元素個數(要pop多少次)
ans.push_back(tt);//這層葉子節點一共有幾個
}
for(int i=0;i<ans.size();i++)
{
if(i!=0)printf(" ");
printf("%d",ans[i]);
}
printf("\n");
}
return 0;
}