PTA数据结构与算法题目集(中文) 7-24
7-24 树种统计 (25 分)
随着卫星成像技术的应用,自然资源研究机构可以识别每一棵树的种类。请编写程序帮助研究人员统计每种树的数量,计算每种树占总数的百分比。
输入格式:
输入首先给出正整数N(≤),随后N行,每行给出卫星观测到的一棵树的种类名称。种类名称由不超过30个英文字母和空格组成(大小写不区分)。
输出格式:
按字典序递增输出各种树的种类名称及其所占总数的百分比,其间以空格分隔,保留小数点后4位。
输入样例:
29
Red Alder
Ash
Aspen
Basswood
Ash
Beech
Yellow Birch
Ash
Cherry
Cottonwood
Ash
Cypress
Red Elm
Gum
Hackberry
White Oak
Hickory
Pecan
Hard Maple
White Oak
Soft Maple
Red Oak
Red Oak
White Oak
Poplan
Sassafras
Sycamore
Black Walnut
Willow
输出样例:
Ash 13.7931%
Aspen 3.4483%
Basswood 3.4483%
Beech 3.4483%
Black Walnut 3.4483%
Cherry 3.4483%
Cottonwood 3.4483%
Cypress 3.4483%
Gum 3.4483%
Hackberry 3.4483%
Hard Maple 3.4483%
Hickory 3.4483%
Pecan 3.4483%
Poplan 3.4483%
Red Alder 3.4483%
Red Elm 3.4483%
Red Oak 6.8966%
Sassafras 3.4483%
Soft Maple 3.4483%
Sycamore 3.4483%
White Oak 10.3448%
Willow 3.4483%
Yellow Birch 3.4483%
题目分析:这是一道利用二叉搜索树的题 将其构造成二叉搜索树 利用中序遍历输出结果
1 #define _CRT_SECURE_NO_WARNINGS 2 #include<stdio.h> 3 #include<string.h> 4 #include<malloc.h> 5 6 typedef struct TreeNode* ptrToTreeNode; 7 struct TreeNode 8 { 9 char Data[35]; 10 ptrToTreeNode LC; 11 ptrToTreeNode RC; 12 int count; 13 }; 14 float Sum; 15 ptrToTreeNode Insert(ptrToTreeNode BT, char Data[35]) 16 { 17 if (!BT) 18 { 19 BT = (ptrToTreeNode)malloc(sizeof(struct TreeNode)); 20 strcpy(BT->Data, Data); 21 BT->count = 1; 22 BT->LC = NULL; 23 BT->RC = NULL; 24 } 25 else 26 { 27 if (strcmp(BT->Data, Data) > 0) 28 BT->LC = Insert(BT->LC, Data); 29 else if (strcmp(BT->Data, Data) < 0) 30 BT->RC = Insert(BT->RC, Data); 31 else 32 BT->count++; 33 } 34 return BT; 35 } 36 37 void InOrder(ptrToTreeNode BT) 38 { 39 if (BT) 40 { 41 InOrder(BT->LC); 42 printf("%s %.4f%%\n", BT->Data, BT->count / Sum*100); 43 InOrder(BT->RC); 44 } 45 } 46 47 int main() 48 { 49 int N; 50 scanf("%d\n", &N); 51 Sum = N; 52 char Data[35]; 53 ptrToTreeNode BT=NULL; 54 for(int i=0;i<N;i++) 55 { 56 gets(Data); 57 BT = Insert(BT, Data); 58 } 59 InOrder(BT); 60 return 0; 61 }
注意一点 gets在c11中被gets_s所取代了