a747簡單字母重排的排序簽章

CPE:Anagrams (II) (UVa 630)

用排序後字串辨識異序詞並保持字典輸入順序。

前往題目練習 →回報教學錯誤N 個字典詞、字長≤L;C++ 有序 map 預處理 O(NL(log(L+1)+log(N+2))),每查詢 O(L(log(L+1)+log(N+2))+輸出字元數),字典空間 O(NL)。Python 雜湊平均預處理 O(NL log(L+1))、每查詢 O(L log(L+1)+輸出字元數),另有 O(T+B) 整份輸入及累積輸出緩衝,T、B 分別為全部輸入與輸出長度。

解題思路

兩個單字能以字母重排互換,等價於每個字母的數量完全相同,也等價於排序後的字串相同。先替字典每個詞計算簽章,查詢時只比較簽章,不需枚舉任何排列。

把同簽章的字典單字依輸入順序存入列表,查詢可直接取整份列表;C++ 用 find、Python 用 get,只讀查詢,不為查無結果的簽章建立空鍵。先印 Anagrams for: word,再由 1 開始編號,編號寬度為 3;沒有結果則印 No anagrams for: word。END 只結束當組查詢,測試組之間留一空行,字典詞本身也可成為答案。

Step-by-step animation

示意:字典 eat、tea、tan,查詢 ate

回報動畫錯誤
步驟 1 / 3

字典簽章

eat、tea 都是 aet,tan 是 ant。

eat→aet
tea→aet
tan→ant
字典數
3

Reference solution

回報程式錯誤

完整程式

#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <algorithm>
#include <iomanip>
using namespace std;
string signature(string s) {
    sort(s.begin(), s.end());
    return s;
}
int main() {
    int t;
    cin >> t;
    for (int cs = 0; cs < t; ++cs) {
        int n;
        cin >> n;
        map<string, vector<string>> dict;
        string s;
        while (n--) {
            cin >> s;
            dict[signature(s)].push_back(s);
        }
        if (cs)
            cout << '\n';
        while (cin >> s && s != "END") {
            cout << "Anagrams for: " << s << '\n';
            auto found = dict.find(signature(s));
            if (found == dict.end())
                cout << "No anagrams for: " << s << '\n';
            else {
                const auto &a = found->second;
                for (size_t i = 0; i < a.size(); ++i)
                    cout << setw(3) << i + 1 << ") " << a[i] << '\n';
            }
        }
    }
}

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

更多