開啟章節選單
10226 Hardwood Species
題目翻譯
每筆測資會給你一串樹種名稱(每行一個名稱),同一筆測資以空行結束。
請統計每種樹出現的比例(百分比),並依字典序輸出:
樹名 百分比,百分比保留小數點後 4 位。
不同測資之間要空一行。
輸入
第一行是一個整數,代表測資案例數量。隨後有一個空行。
每個案例包含一系列樹木名稱,每行一個名稱(長度最多 30 字元)。
每個案例以空行結束(或文件結束)。一個案例中樹木總數最多 1,000,000 棵,種類最多 10,000 種。
輸出
依據品種名稱的**字典序(升冪)**列出所有品種。
名稱後方輸出該品種佔總數的百分比,精確到小數點後 4 位。
每個案例的輸出之間請留一個空行。
解題思路
這題重點是字串統計與輸出格式:
- 用
getline逐行讀入一筆測資,遇到空行就結束該筆。 - 用
map<string, int>記錄每個樹名出現次數,同時累計總筆數total。 map會自動依字典序排序,直接走訪並輸出:100.0 * 次數 / total,搭配fixed << setprecision(4)。
程式前面的兩次 cin.ignore() 是為了跳過題目輸入中測資數量後面的換行與空行,避免第一筆讀取錯位。
程式碼
#include <bits/stdc++.h> using namespace std; #define int long long #define idonthavegirlfriend ios::sync_with_stdio(0), cin.tie(0); #define pb push_back #define yn(a) (a ? "Yes\n" : "No\n") // #include <atcoder/fenwicktree> // #include <atcoder/dsu> // using namespace atcoder // author:Jackis666 signed main() { idonthavegirlfriend int t; cin >> t; cin.ignore(); cin.ignore(); while (t--) { string in; map<string, int> mp; int total = 0; while (getline(cin, in), in != "") { mp[in]++; total++; } for (auto v : mp) { cout << v.first << " " << fixed << setprecision(4) << (double)100 * v.second / total << "\n"; } if (t) cout << "\n"; } }