題目: UVa - 10226 - Hardwood Species

題目說明

測資開始於一個整數,代表接下來會有幾組資料,一開始的整數後及每組資料間都有空行隔開,可見 Sample I/O。

Input: 每組資料會有許多行字串,每個字串代表一種樹木,出現的次數即為樹木的數量。直到讀取到空的字串為止。

Output: 輸出每種樹木的名字及所佔的百分比 ( 順序為樹木名字的升冪排序,百分比輸出到小數點後四位 ),每組輸出的資料中間需有空行隔開。

解題思路

先讀取最前面的整數,由於接下來要使用 getline(),所以先呼叫 cin.ingore() 將輸入流中的 '\n' 清除,再呼叫一次 getline() 讀取整數與第一組資料間的空行,接著就可以開始讀取資料,使用 map 紀錄一組資料中的各個樹木種類出現的次數,同時需要紀錄樹木的總數,最後計算百分比並輸出即可。

參考解法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <iostream>
#include <string>
#include <map>
#include <iomanip>

using namespace std;

// fast IO
static auto __ = []()
{
std::ios_base::sync_with_stdio(false);
std::cin.tie(nullptr);
std::cout.tie(nullptr);
return 0;
}();

int main()
{
int c;
string str;

cin >> c;
cin.ignore();
// avoid space
getline(cin, str);

while (c--)
{
double cnt = 0;
string str;
map<string, double> m;

while (getline(cin, str) && !str.empty()) ++m[str], ++cnt;

for (auto& [tree, num] : m)
cout << tree << " " << setprecision(4) << fixed << num * 100 / cnt << '\n';

if(c) cout << '\n';
}
}