菜鸟练习PAT(四)

来源:互联网 发布:优化网站的文件和资源 编辑:程序博客网 时间:2024/04/26 10:21

题目标号:A-1004

感觉这道题目主要是考树的存储和遍历。本来以为用不到树来存储,就直接记录每个level的叶子结点数,但总是有2个测试点过不了。后来发现是因为OJ输出双亲与孩子的时候不一定是从上至下的哭。于是写了个邻接表存储这棵树,当存储完毕时遍历就可以了。(关于树请移步: 树系列之二:树的存储结构 。

题目:


菜鸟代码:

#include "stdio.h"#include "stdlib.h"#define MAXNUM 100typedef struct Node {int child;struct Node *node;}Parent ;int level[MAXNUM] = {0} ;//to store the level leaf childint ID[MAXNUM]  = {0};//to store the level of the nodeint leafExist[MAXNUM] = {0} ;//to mark if the leaf existParent *parents[MAXNUM] ;//to store the tree// convert string to numberint getDigitValue(char s[]){int value = 0;value = ( (s[0] - 48)*10 + s[1] - 48 ) ;return value;}int main(void){int allCnt , noLeaCnt , i , num ,count ; char chNum[2] ;//init the data for the rootlevel[1] = ID[1] = 1;leafExist[1] = 1;scanf("%d %d" , &allCnt , &noLeaCnt);// the below is to store the tree in the array parents[]for( i =0 ; i <noLeaCnt ; i++ ){Parent *P = (Parent*)malloc(sizeof(Parent));Parent *head = P ;scanf("%s %d" , chNum , &count);num = getDigitValue(chNum);parents[num] = head ;P->child = num ;P->node = NULL ;while(count--){int temp ;Parent *node = (Parent*)malloc(sizeof(Parent));scanf("%s" , chNum);temp =  getDigitValue(chNum) ;node->child = temp ;node->node = NULL ;P->node = node ;P = P->node;}}// to digest the array for( i = 0 ; i <= allCnt ; i ++){if(parents[i] == NULL) continue;else{int head ;Parent *p = parents[i] ;head = p->child ;p = p->node ;if(p!=NULL)level[ID[head]] -- ;while(p!=NULL){int temp ;temp = p->child ;ID[temp] = ID[head] + 1 ;level[ID[temp]] ++;leafExist[ID[temp]] = 1 ;p = p->node ;}}}// print the result in orderfor( i = 1 ; ; i++){if(leafExist[i + 1] == 0) break;printf("%d " , level[i]);}printf("%d\n" , level[i]);return 0;}


0 0