POJ_2418

此题中物种名(关键字)与该物种的棵树(关键字值)是一对一的数据关系。由于map库会自动排序关键字,因此h表采用map类的关联容器,使得表元素自动按照物种的字典序排列,这样可以避免输出前编程排序物种的麻烦。
#include<iostream>
#include<string>
#include<map>
#include<cstdio>
#include<algorithm>
using namespace std;
typedef map<string ,int > record;  //record为map基本容器
record h; //树名x的棵数为h[x]
string s;//树名串;
int n;
int main()
{
    n=0;//树木总数的初始化
    while(getline(cin,s)){  //输入物种列表,统计树木总数和每类物种的数目棵树
        n++;
        h[s]++;
    }
    for(record::iterator it=h.begin();it!=h.end();it++)  //顺序搜索h表中的每个物种(h表按照物种的在字典序排序)
    {
        string name =(*it ).first;  //取当前树名
        int k=(*it).second; //取该类树的棵树
        printf("%s %.4lf\n",name.c_str(),double(k)*100/double(n)); //输出树名和该树在树中所占的比例
    }
}

猜你喜欢

转载自blog.csdn.net/qq_41999763/article/details/80722948
POJ
今日推荐