时间限制 400 ms 内存限制 65536 kB 代码长度限制 16000 B 判题程序 Standard 作者 CHEN, Yue A family hierarchy is usually presented by a pedigree tree. Your job is to count those family members who have no child. Input
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. Output
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=2,M=1
01有一个孩子02,
然后输出每一层的叶子数。
第一层0 第二层1
#include<iostream> #include<queue> using namespace std; int dep[120][120]; int n,m,k; int tt[120]; int maxleval=-1; void bfs(int number,int leval)//number 为每个人的编号,leval为层数 { if (maxleval<leval)//记录最大层数 { maxleval=leval; } int temp=number; int node=0; for (int i=1;i<=n;i++) { if(dep[temp][i]==1)//i是tmep的孩子 { int sum=0;//判断i是否有孩子 for (int j=1;j<=n;j++) { sum+=dep[i][j]; } if (sum==0)//如果没有当前层的叶子数量加一 { tt[leval]++; } else { bfs(i,leval+1);//否则进入下一层 } } } } int main() { int a,b; cin>>n>>m; for (int i=1;i<=m;i++) { cin>>a; cin>>k; for (int i=0;i<k;i++) { cin>>b; dep[a][b]=1; } } bfs(1,1); if (m==0)//当只有一个人时,他本身也是一个叶子节点 { cout<<1; return 0; } else cout<<0; for (int i=1;i<=maxleval;i++) { cout<<" "<<tt[i]; } return 0; }精简代码之后
#include<iostream> #include<vector> using namespace std; int maxleval=-1; vector <int> v[110]; int anslev[110]; void bfs(int now,int leval) { maxleval=max(maxleval,leval); for (int i=0;i<v[now].size();i++) { if (v[v[now][i]].size()==0) anslev[leval]++; else bfs(v[now][i],leval+1); } } int main() { int n,m; int t,tt,sum; cin>>n>>m; for (int i=0;i<m;i++) { cin>>t>>sum; for(int i=0;i<sum;i++) { cin>>tt; v[t].push_back(tt); } } bfs(1,1); if (m==0) { cout<<1; return 0; } cout<<0; for (int i=1;i<=maxleval;i++) cout<<" "<<anslev[i]; return 0; }