Description
随着卫星成像技术的应用,自然资源研究机构可以识别每一个棵树的种类。请编写程序帮助研究人员统计每种树的数量,计算每种树占总数的百分比。
Input
输入一组测试数据。数据的第1行给出一个正整数N (n <= 100000),N表示树的数量;随后N行,每行给出卫星观测到的一棵树的种类名称,树的名称是一个不超过20个字符的字符串,字符串由英文字母和空格组成,不区分大小写。
Output
按字典序输出各种树的种类名称和它占的百分比,中间以空格间隔,小数点后保留两位小数。
Sample
Input
2
This is an Appletree
this is an appletree
Output
this is an appletree 100.00%
答案:
#include <iostream>
#include<bits/stdc++.h>
#define ll long long
#define INf 0x3f3f3f3f
const int N = 25;
using namespace std;
int n;
struct node
{
char name[N];
int cnt;
node *l,*r;
};
void buildtree(node *&root,char str[]) //建树
{
if(!root)
{
root=new node;
strcpy(root->name,str);
root->cnt=1;
root->l=NULL;
root->r=NULL;
}
else
{
int temp=strcmp(root->name,str);
if(temp>0)
buildtree(root->l,str);
else if(temp<0)
buildtree(root->r,str);
else
root->cnt++;
}
}
void midorder(node *root) //中序遍历
{
if(root)
{
midorder(root->l);
printf("%s %.2lf%%\n",root->name,100.0*root->cnt/n);
midorder(root->r);
}
}
int main()
{
int t;
cin>>t;
getchar(); //很重要!
n=t;
node *root=NULL;
char s[N];
while(t--)
{
gets(s);
int len=strlen(s);
int i;
for(i=0; i<len; i++) //大写变小写
{
if(s[i]>='A'&&s[i]<='Z')
s[i]+='a'-'A';
}
buildtree(root,s);
}
midorder(root);
return 0;
}
STL map映射:
#include <iostream>
#include<bits/stdc++.h>
#define ll long long
#define INf 0x3f3f3f3f
const int N = 1e5 + 10;
using namespace std;
map<int,string>mp;
int vis[N];
char s[111];
void change(int n) //大写变小写
{
int i;
for(i=0; i<n; i++)
{
if(s[i]>='A'&&s[i]<='Z')
{
s[i]+='a'-'A';
}
}
}
int main()
{
int n;
cin>>n;
getchar();
memset(vis,0,sizeof(vis));
int pos=0;
for(int i=0; i<n; i++) //map映射
{
gets(s);
int len=strlen(s);
change(len);
bool flag=0;
for(int i=0; i<pos; i++)
{
if(mp[i]==s)
{
flag=1;
vis[i]++;
break;
}
}
if(!flag)
{
mp[pos]=s;
vis[pos]++;
pos++;
}
}
string str;
int k;
for(int i=0; i<pos-1; i++) //排序
{
for(int j=i+1; j<pos; j++)
{
if(mp[j]<mp[i])
{
str=mp[i];
mp[i]=mp[j];
mp[j]=str;
k=vis[i];
vis[i]=vis[j];
vis[j]=k;
}
}
}
for(int i=0; i<pos; i++)
{
cout<<mp[i]<<" ";
printf("%.2f%%\n",vis[i]*100.0/n);
}
return 0;
}