a318簡單依編號累計・兩層排序鍵
TOI 2019/10 潛力組:粉絲見面會
累計每位粉絲的贈禮,再用金額降序與編號升序決定名次。
解題思路
先配置 N 個初始為 0 的總金額。每筆紀錄只把金額加到該粉絲的格子;讀完後,陣列中每格就是該人的完整總額。沒有出現的編號仍保留 0,不能只輸出有贈禮的人。
把所有編號排序,比較時先看總額,較大者優先;相同總額再比較編號,較小者優先。Python 可以使用鍵 (−total[id],id);C++ 的比較函式明確實作兩個條件。輸出的是編號與累計金額,不是輸入紀錄的逐筆排名。
Step-by-step animation
公開範例:累計與平手排序
步驟 1 / 3
前兩筆紀錄
粉絲 2 收到 10,粉絲 0 收到 7。
0:7
1:0
2:10
3:0
- 已處理
- 2筆
#include <iostream>
#include <vector>
#include <numeric>
#include <algorithm>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n, m;
cin >> n >> m;
vector<long long> total(n);
while (m--) {
int id, x;
cin >> id >> x;
total[id] += x;
}
vector<int> order(n);
iota(order.begin(), order.end(), 0);
sort(order.begin(), order.end(),
[&](int a, int b) { return total[a] != total[b] ? total[a] > total[b] : a < b; });
for (int id : order)
cout << id << ' ' << total[id] << '\n';
}先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。