a534困難反向還原排列的 Lehmer 編碼

CPE:Lexicographic Order (UVa 12335)

由排列名次推知每個字母在剩餘字母中的排名。

前往題目練習 →回報教學錯誤每筆時間 O(n²),空間 O(n)。

解題思路

將 k 改成從零開始的 rank=k−1。首字母在尚未決定的字母中,前面每一個較小字母都會產生 (n−1)! 個排列,因此 rank//(n−1)! 就是 s[0] 在剩餘字母中的相對排名;餘數交給下一個位置,以此類推。

這次並不知道字母表本身,維護的是由小至大排列的空槽。每次取相對排名指向的空槽,把當前字母填入,再刪除該槽。所有位置完成後按槽順序讀出外星字母表。20! 小於 2⁶³,C++ long long 足夠;輸出 Case i: alphabet。

Step-by-step animation

示意:s=bac、k=3

回報動畫錯誤
步驟 1 / 3

首字母排名

rank=2,2!=2,b 在剩餘字母中排名 1。

空槽0
b
空槽2
rank
0
空槽
0,2

Reference solution

回報程式錯誤

完整程式

#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <algorithm>
#include <numeric>
#include <cmath>
#include <iomanip>
#include <queue>
#include <deque>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <array>
#include <tuple>
#include <functional>
#include <limits>
#include <cstdint>
#include <cctype>
#include <utility>
using namespace std;

int main() {
    long long fact[21] = {1};
    for (int i = 1; i <= 20; ++i)
        fact[i] = fact[i - 1] * i;
    int t;
    cin >> t;
    for (int tc = 1; tc <= t; ++tc) {
        string s;
        long long k;
        cin >> s >> k;
        --k;
        int n = s.size();
        vector<int> slots(n);
        iota(slots.begin(), slots.end(), 0);
        string ans(n, '?');
        for (int i = 0; i < n; ++i) {
            long long f = fact[n - i - 1];
            int r = int(k / f);
            k %= f;
            ans[slots[r]] = s[i];
            slots.erase(slots.begin() + r);
        }
        cout << "Case " << tc << ": " << ans << '\n';
    }
}

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

更多