7-12 树种统计
程序员文章站
2022-05-20 09:38:13
...
随着卫星成像技术的应用,自然资源研究机构可以识别每一棵树的种类。请编写程序帮助研究人员统计每种树的数量,计算每种树占总数的百分比。
输入格式:
输入首先给出正整数N(≤105),随后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%
分析:
开始一直用排序做,一直wa,看了大神的代码才恍然大悟
代码:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
struct node{
char name[35];
int num;
struct node * left;
struct node * right;
};
typedef struct node * Tree;
int n;
Tree creatTree(Tree root,char name[]){
if(root==NULL){
root=(Tree)malloc(sizeof(struct node));
strcpy(root->name,name);
root->num=1;
root->left=NULL;
root->right=NULL;
}
else{
int cmp=strcmp(name,root->name);
if(cmp<0) root->left=creatTree(root->left,name);
else if(cmp>0) root->right=creatTree(root->right,name);
else root->num=root->num+1;
}
return root;
}
void inOrder(Tree root){
if(root){
inOrder(root->left);
printf("%s %.4f%%\n",root->name,root->num*1.0*100/n);
inOrder(root->right);
}
}
int main(){
scanf("%d",&n);
getchar();
Tree root= NULL;
for(int i=0;i<n;i++){
char s[35];
gets(s);
root=creatTree(root,s);
}
inOrder(root);
return 0;
}