a585困難Move-to-front與Fenwick排名查詢

CPE:Uncompress (UVa 245)

用時間槽維護單字清單,支援無上限字典的快速解壓縮。

前往題目練習 →回報教學錯誤總時間 O(L+P log P),空間 O(L+P),L為文字長度、P為單字與引用次數。

解題思路

先將文字切成英文字母段、十進位數字段與其他字元段,單字大小寫有別,非字母符號與換行原樣輸出。文字單字是首次出現的新詞,加入清單最前;數字k則取目前清單第k個詞,輸出它後移到最前。位置是當下的排名,不能當成首次出現的固定編號。

為避免每次搬動長清單,先計算單字與引用的總次數P,準備P個槽,由大到小分配新槽;槽號越小代表越新。Fenwick樹以1標記仍在清單中的槽,前綴和表示排名,可用二進位提升找第k個1。引用時將舊槽減1,再給該詞一個更小的新槽並加1。原文字串與槽共O(L)空間,單獨一行0終止而不輸出。

Step-by-step animation

示意:壓縮文字『red blue 2 2』

回報動畫錯誤
步驟 1 / 3

讀兩個新詞

先red後blue,清單前到後為blue、red。

1:blue
2:red
已輸出單字
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;

bool letter(char c) {
    return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z');
}
bool digit(char c) {
    return c >= '0' && c <= '9';
}
struct Fenwick {
    int n;
    vector<int> tree;
    Fenwick(int size) : n(size), tree(size + 1) {}
    void add(int p, int delta) {
        for (; p <= n; p += p & -p)
            tree[p] += delta;
    }
    int kth(int k) {
        int p = 0, step = 1;
        while (step <= n / 2)
            step *= 2;
        for (; step; step /= 2) {
            int next = p + step;
            if (next <= n && tree[next] < k) {
                p = next;
                k -= tree[next];
            }
        }
        return p + 1;
    }
};
int main() {
    string text, line;
    while (getline(cin, line) && line != "0")
        text += line + '\n';
    int count = 0;
    for (size_t i = 0; i < text.size();) {
        if (letter(text[i]) || digit(text[i])) {
            bool word = letter(text[i]);
            ++count;
            do {
                ++i;
            } while (i < text.size() && (word ? letter(text[i]) : digit(text[i])));
        } else
            ++i;
    }
    Fenwick bit(count);
    vector<string> at(count + 1);
    int next = count;
    for (size_t i = 0; i < text.size();) {
        if (!letter(text[i]) && !digit(text[i])) {
            cout << text[i++];
            continue;
        }
        bool word = letter(text[i]);
        size_t start = i;
        do {
            ++i;
        } while (i < text.size() && (word ? letter(text[i]) : digit(text[i])));
        string token = text.substr(start, i - start), value;
        if (word)
            value = token;
        else {
            int old = bit.kth(stoi(token));
            value = move(at[old]);
            bit.add(old, -1);
        }
        cout << value;
        at[next] = move(value);
        bit.add(next, 1);
        --next;
    }
}

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

更多