a482中等整行樹名計數與排序百分比
CPE:Hardwood Species (UVa 10226)
保留名稱空白,按資料區塊統計樹種比例。
解題思路
每一行代表一棵樹,名稱中的空白屬於鍵的一部分,因此以整行字串作為映射鍵,計數加1並累加總棵數。資料區塊由空行分隔,第一行的測試筆數與緊接的空行不屬於樹名。
讀完整組後按名稱字典序輸出,每種比例為100×count/total,固定四位小數且不印百分號。C++用map同時維護排序;Python用dict計數後排序鍵,避免保存最多一百萬行的原始清單。兩組輸出之間恰有一空行,最後一組可直接到EOF。
Step-by-step animation
示意:Oak、Red Elm、Oak
步驟 1 / 3
讀Oak
Oak的計數變成1,總數1。
Oak:1
- total
- 1
#include <iostream>
#include <string>
#include <map>
#include <iomanip>
#include <limits>
using namespace std;
int main() {
int T;
cin >> T;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << fixed << setprecision(4);
for (int tc = 0; tc < T; ++tc) {
map<string, int> count;
string s;
int total = 0;
while (getline(cin, s)) {
if (!s.empty() && s.back() == '\r')
s.pop_back();
if (s.empty()) {
if (total)
break;
else
continue;
}
++count[s];
++total;
}
if (tc)
cout << '\n';
for (const auto &entry : count)
cout << entry.first << ' ' << 100.0 * entry.second / total << '\n';
}
}先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。