a651中等串接比較器與相鄰交換

CPE:Children’s Game (UVa 10905)

以 ab 與 ba 的大小決定數字字串的最佳順序。

前往題目練習 →回報教學錯誤時間 O(N log N·L),空間 O(NL),L 為單數字最大位數。

解題思路

兩個數字字串 a、b 的順序只能影響局部串接 ab 或 ba。若 ab>ba,就應讓 a 在 b 前;交換這一對不改變總長度,也不改變其他字元,因此能讓整體結果更大。依此比較器排序,再直接串接所有字串。

不能按整數值或一般字典序排序,例如 9 與 90,990 比 909 大,因此 9 要先放。比較器可理解為比較無限重複字串 aaaa… 與 bbbb…,具有排序所需的一致性;ab=ba 時兩種順序輸出完全相同。輸入與答案都以字串保存,不受整數位數限制;N=0 結束。

Step-by-step animation

示意:9、90、56

回報動畫錯誤
步驟 1 / 3

比較 9、90

990>909,所以 9 應在 90 前。

990
909
較佳順序
9,90

Reference solution

回報程式錯誤

完整程式

#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main() {
    int n;
    while (cin >> n && n) {
        vector<string> a(n);
        for (auto &s : a)
            cin >> s;
        sort(a.begin(), a.end(), [](const string &x, const string &y) { return x + y > y + x; });
        for (auto &s : a)
            cout << s;
        cout << '\n';
    }
}

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

更多