您的位置:首页 > 其它

POJ2418 Hardwood Species

2012-09-15 10:18 183 查看
  原题传送:http://poj.org/problem?id=2418

  用的是STL神器,map + priority_queue。(C++提交和G++提交相差6s !)

View Code

#include <map>
#include <queue>
#include <string>
#include <iostream>
#include <iterator>
#include <stdio.h>
using namespace std;

typedef pair<string, double> psi;

int main()
{
string s;
map<string, int> m;
priority_queue<psi, vector<psi>, greater<psi> > q;
int sum = 0;
while(getline(cin, s) != NULL)
{
if(m.find(s) == m.end())
m[s] = 1;
else
m[s] ++;
sum ++;
}
psi tmp;
for (map<string, int>::iterator iter = m.begin(); iter != m.end(); ++iter)
{
tmp.first = iter->first;
tmp.second = (iter->second + 0.0) / sum;
q.push(tmp);
}
while(!q.empty())
{
cout << q.top().first << " ";
printf("%.4f\n", q.top().second * 100);
q.pop();
}
return 0;
}


  这题更好的一个做法是用排序二叉树,根据排序二叉树的性质:

  若他的左子树不空,则左子树上所有的结点均小于它的根结点的值。

  若他的右子树不空,则右子树上所有的结点均大于它的根结点的值。

  他的左右子树也是排序二叉树。

  

  在构造完成排序二叉树后进行一次中序遍历就可以了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: