a639中等欄位交集與混合進位字典序反排名

CPE:Password (UVa 1262)

直接取得第 K 個不同密碼,不重複枚舉相同欄字母。

前往題目練習 →回報教學錯誤每組 O(60+5·26 log 26) 時間,O(5·26) 空間。

解題思路

每一欄可用字母必須同時出現在兩張表的該欄,因此先做集合交集並排序。各欄彼此獨立,密碼總數等於五個欄位候選數的乘積;某欄為空就完全無解。重複列字母只算一次。

把 K 改成零起算順位 r=K−1。固定當前欄一個字母後,後面所有欄形成 block 個組合,所以當前字母索引為 r//block,再更新 r%=block;逐欄如此就得到字典序第 K 個。若 K 大於總數先輸出 NO,避免除以零或越界。每組精確讀入兩份六行五欄表格。

Step-by-step animation

示意:五欄候選 {A,B}、{C,D}、{E}、{F}、{G},K=3

回報動畫錯誤
步驟 1 / 3

零起算

共 2×2×1×1×1=4 組,r=2。

AB
CD
E
F
G
r
2
總數
4

Reference solution

回報程式錯誤

完整程式

#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main() {
    int t;
    cin >> t;
    while (t--) {
        int k;
        cin >> k;
        vector<string> a(6), b(6);
        for (auto &s : a)
            cin >> s;
        for (auto &s : b)
            cin >> s;
        vector<string> options(5);
        for (int c = 0; c < 5; ++c)
            for (char ch = 'A'; ch <= 'Z'; ++ch) {
                bool x = false, y = false;
                for (int r = 0; r < 6; ++r) {
                    x |= a[r][c] == ch;
                    y |= b[r][c] == ch;
                }
                if (x && y)
                    options[c] += ch;
            }
        int total = 1;
        for (auto &s : options)
            total *= s.size();
        if (k > total) {
            cout << "NO\n";
            continue;
        }
        int rank = k - 1;
        string answer;
        for (int c = 0; c < 5; ++c) {
            int block = 1;
            for (int j = c + 1; j < 5; ++j)
                block *= options[j].size();
            answer += options[c][rank / block];
            rank %= block;
        }
        cout << answer << '\n';
    }
}

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

更多