a702簡單逆序評分與穩定排序

CPE:DNA Sorting (UVa 612)

依字串無序程度排序,同分維持原順序。

前往題目練習 →回報教學錯誤m條長n字串,時間 O(mn²+m log m),空間 O(mn)。

解題思路

對每條長度n≤50的DNA,直接枚舉i<j,比較s[i]>s[j]時將逆序數加1。字元A<C<G<T的編碼順序符合題意,重複相等字元不構成逆序。這個分數只描述字串,不需要真的排序其內部字元。

以逆序數為唯一排序鍵做穩定排序,就能讓同分字串保持原輸入先後。C++使用stable_sort,Python的sort本身穩定;避免把字串字典序當成第二個鍵。輸入有組數與空白行,分詞讀取會自然忽略空白;兩組輸出之間空一行,組內每條字串一行。

Step-by-step animation

示意:輸入 TAAA、ACGT、CAAA

回報動畫錯誤
步驟 1 / 3

TAAA

T與後面三個A各成逆序,分數3。

T
A
A
A
逆序
3
輸入序
0

Reference solution

回報程式錯誤

完整程式

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
int main() {
    int tests;
    cin >> tests;
    for (int tc = 0; tc < tests; tc++) {
        int n, m;
        cin >> n >> m;
        vector<pair<int, string>> a;
        for (int k = 0; k < m; k++) {
            string s;
            cin >> s;
            int score = 0;
            for (int i = 0; i < n; i++)
                for (int j = i + 1; j < n; j++)
                    score += s[i] > s[j];
            a.push_back({score, s});
        }
        stable_sort(a.begin(), a.end(),
                    [](const auto &x, const auto &y) { return x.first < y.first; });
        if (tc)
            cout << '\n';
        for (auto &row : a)
            cout << row.second << '\n';
    }
}

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

更多