b128簡單

110 新北市資訊學科能力競賽複賽(2021)|報表排序

每批先建立代號與內容的一一對應配對。

解題思路

每批先建立代號與內容的一一對應配對。

使用(代號,數值)作排序鍵,第一項不同時依ASCII字典序,相同時才比較數值。

每批獨立排序後立即輸出;代號行的長度決定當批報表數。

每批k筆,時間 O(k log k),空間 O(k),另計代號字元長度。

Step-by-step animation

教學小例:配對排序與整行讀取

回報動畫錯誤
步驟 1 / 3

原始配對

aa 9、a01 3、aa 2

aa 9、a01 3、aa 2
步驟
1

Reference solution

回報程式錯誤

完整程式

#include <bits/stdc++.h>
using namespace std;
int main() {
    int t;
    cin >> t;
    string s;
    getline(cin, s);
    while (t--) {
        getline(cin, s);
        stringstream ss(s);
        vector<string> names;
        while (ss >> s)
            names.push_back(s);
        getline(cin, s);
        stringstream nums(s);
        vector<pair<string, int>> v;
        for (auto c : names) {
            int x;
            nums >> x;
            v.push_back({c, x});
        }
        sort(v.begin(), v.end());
        for (auto [c, x] : v)
            cout << c << ' ' << x << '\n';
    }
}

先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。

更多