数据结构实验之查找三:树的种类统计
Time Limit: 400MS
Memory Limit: 65536KB
Problem Description
随着卫星成像技术的应用,自然资源研究机构可以识别每一个棵树的种类。请编写程序帮助研究人员统计每种树的数量,计算每种树占总数的百分比。
Input
输入一组测试数据。数据的第1行给出一个正整数N (n <= 100000),N表示树的数量;随后N行,每行给出卫星观测到的一棵树的种类名称,树的名称是一个不超过20个字符的字符串,字符串由英文字母和空格组成,不区分大小写。
Output
按字典序输出各种树的种类名称和它占的百分比,中间以空格间隔,小数点后保留两位小数。
Example Input
2 This is an Appletree this is an appletree
Example Output
this is an appletree 100.00%
此题就是记录相同的字符串的数目,只是用树的结构来组织,把所有的大写字母转化成小写字母是为了方便比较。
#include<bits/stdc++.h> using namespace std; char a[35]; int n; struct bittree{ char data[35]; int num; //记录该字符串出现的次数 bittree *lchild, *rchild; }; bittree *Creat(bittree *root){ if(!root){ root = new bittree; root->lchild = NULL; root->rchild = NULL; root->num = 1; strcpy(root->data, a); } else{ if(strcmp(a, root->data) == 0) root->num++; else if(strcmp(a, root->data)<0) root->lchild = Creat(root->lchild); else root->rchild = Creat(root->rchild); } return root; } void Inorder(bittree *root){ if(root){ Inorder(root->lchild); printf("%s %.2lf%%\n", root->data,(1.0*root->num*100)/n); //注意在printf里的百分号要使用%%转义 Inorder(root->rchild); } } int main(){ bittree *root =NULL; cin>>n; getchar(); //吞掉一个换行 for(int k=0; k<n; k++){ gets(a); //gets()以Enter结束输入(空格不结束),接受空格,会舍弃最后的回车符! int len = strlen(a); for(int i=0; i<len; i++) a[i] = tolower(a[i]); //大写字母转化为小写字母的函数 root = Creat(root); } Inorder(root); return 0; }