我的程序在运行时部分正确,但是我不知道哪里错了,麻烦大家帮我看看。
这是题目:1004 Counting Leaves (30)(30 分)
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 levelstarting 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
程序:#include<stdio.h>
int a[100];
int c[100];
int b[100];
int num[100];
int main(){
int n,m;
int i,j,k=0,t=0,r=0;
scanf("%d %d",&n,&m);
if(n!=1){
for(i=0;i<n-m;i++){
scanf("%d %d",&a[i],&c[i]);
for(j=0;j<c[i];j++,k++){
scanf("%d",&b[k]);
}
}
k=0;
i=c[0];
do{
for(;i>0;i--,t++){
for(j=0;j<n;j++){
if(a[j]==b[t]){
k+=c[j];
break;
}
}
if(j==n && a[j-1]!=b[t])
num[r]++;
}
i=k;
r++;
}while(b[t]!=0);
printf("0");
for(i=0;i<r;i++){
printf(" %d",num[i]);
}
}
else if(n==1){
scanf("%d",&a[0]);
printf("%d",1);
}
}
具体思路:将父母放在a数组,对应的子女放在b数组,子女个数放在c数组,然后遍历每一层子女是否有后代。其中根节点的后代不用遍历直接输出0,n为1,m为0的情况单独考虑。
2023/11/16
时隔多年...这个问题还是我自己来解答吧!
这个题目出的实在是不严谨 漏洞太多 pass~