POJ2418 Hardwood Species

  原题传送:http://poj.org/problem?id=2418

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

View Code
 1 #include <map>
 2 #include <queue>
 3 #include <string>
 4 #include <iostream>
 5 #include <iterator>
 6 #include <stdio.h>
 7 using namespace std;
 8 
 9 typedef pair<string, double> psi;
10 
11 int main()
12 {
13     string s;
14     map<string, int> m;
15     priority_queue<psi, vector<psi>, greater<psi> > q;
16     int sum = 0;
17     while(getline(cin, s) != NULL)
18     {
19         if(m.find(s) == m.end())
20             m[s] = 1;
21         else
22             m[s] ++;
23         sum ++;
24     }
25     psi tmp;
26     for (map<string, int>::iterator iter = m.begin(); iter != m.end(); ++iter)
27     {
28         tmp.first = iter->first;
29         tmp.second = (iter->second + 0.0) / sum;
30         q.push(tmp);
31     }
32     while(!q.empty())
33     {
34         cout << q.top().first << " ";
35         printf("%.4f\n", q.top().second * 100);
36         q.pop();
37     }
38     return 0;
39 }

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

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

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

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

  

  在构造完成排序二叉树后进行一次中序遍历就可以了。

原文地址:https://www.cnblogs.com/huangfeihome/p/2686014.html