b596中等

CSES 1149|相異子序列(Distinct Subsequences)

記錄每個字母前一次出現前的總數,避免同內容子序列重複計算。

解題思路

令 total 包含空字串,初值為 1。加入新字元 c 時,舊有每個子序列都可選擇不加 c 或在末尾加 c,初步得到 2·total 種。若 c 曾出現,會重複生成那些在前一次 c 之前形成、再接上 c 的字串。

令 last[c] 保存處理前一次 c 之前的 total,本次新總數為 2·total−last[c],再把舊 total 存入 last[c]。每個重複字串必定以 c 結尾,且刪掉尾 c 後唯一對應前一次出現之前的子序列,故扣除不多不少。最後扣掉唯一空字串。

時間 O(n)、DP 空間 O(26),Python 輸入字串緩衝 O(n);n≤500000,所有運算模 1000000007。

Step-by-step animation

獨立教學例子(不一定是公開範例)

回報動畫錯誤
步驟 1 / 3

步驟 1:開始只有空字串

開始只有空字串

ε
total
1

Reference solution

回報程式錯誤

完整程式

#include <bits/stdc++.h>
using namespace std;
using ll = long long;
const ll MOD = 1000000007;
int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    string s;
    cin >> s;
    array<ll, 26> last{};
    ll total = 1;
    for (char c : s) {
        ll old = total;
        total = (2 * total - last[c - 'a'] + MOD) % MOD;
        last[c - 'a'] = old;
    }
    cout << (total - 1 + MOD) % MOD << '\n';
}

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

更多