PAT甲级1004 数组
题目
1004. Counting Leaves (30)
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 Input2 1 01 1 02Sample Output
0 1
题目大意是给定一棵树,求这棵树每层的叶子节点个数
n为树的节点总数,m为非叶子节点个数,接下来的m行每行的输入为ID(结点) K(结点孩子数) ID[1](孩子1) ID[2](孩子2) ... ID[K](孩子k)
题意很明显要用树来写,数组也能实现,代码如下
#include<iostream> #include<cstdio> #include<cstring> using namespace std; int tree[105][105]; int no[105]; //每层的叶子数 int n,m; int ma; //最大层数 void dfs(int s) { for(int i=1;i<=n;i++) { if(tree[s][i]) { if(tree[i][0]!=(tree[s][0]+1)) { tree[i][0]=tree[s][0]+1; if(tree[i][0]>ma)ma=tree[i][0]; } dfs(i); } } } int main() { int a,b,c; while(scanf("%d%d",&n,&m)!=EOF) { memset(no,0,sizeof(no)); memset(tree,0,sizeof(tree)); ma=1; tree[1][0]=1; //第一个元素存放该节点的层数 for(int i=0;i<m;i++) { scanf("%d%d",&a,&b); tree[a][104]=b; for(int j=0;j<b;j++) { scanf("%d",&c); tree[a][c]=1; } } dfs(1); for(int i=1;i<=n;i++) { if(tree[i][104]==0) { no[tree[i][0]]++; } } for(int i=1;i<=ma;i++) { printf("%d",no[i]); if(i!=ma)printf(" "); } printf("\n"); } return 0; }
大概思路是使用一个(n+2)*(n+2)的二维数组,每行第一位存该节点的层数,最后一位存孩子数,如果j为结点i的孩子,那么将tree[i][j]置为1。
将整棵树输入完毕后从根节点开始深搜标记每个节点的层数,完成后遍历每行的最后一个元素将叶子节点记录下来。