a695困難末項排名DP與前綴和加速

CPE:Number String (UVa 1650)

計算長達1000個升降條件的排列數,無須枚舉排列。

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

解題思路

處理k個數時,dp[r]表示最後一個數在這k個數中的0起算排名為r的合法排列數。加入新末項後,它在k+1個數中的排名可為j。原末項排名若小於j,在插入新數後仍比新末項小;若大於等於j,重新編號後會比新末項大。

因此I的轉移是 sum(dp[r],r<j),D是 sum(dp[r],r≥j),?則可接所有舊排列。用前綴和prefix[j]與總和計算這兩段,每次條件O(k)即可;初始只有一個數,dp=[1]。每步取模1000000007,最後加總所有末項排名。輸入字串長度L,實際排列長度是L+1,讀到EOF。

Step-by-step animation

示意:特徵字串 ID

回報動畫錯誤
步驟 1 / 3

一個數

長度1只有排名0,計數1。

rank0:1
k
1

Reference solution

回報程式錯誤

完整程式

#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main() {
    const long long mod = 1000000007;
    string s;
    while (cin >> s) {
        vector<long long> dp(1, 1);
        for (char ch : s) {
            int k = dp.size();
            vector<long long> prefix(k + 1), next(k + 1);
            for (int i = 0; i < k; i++)
                prefix[i + 1] = (prefix[i] + dp[i]) % mod;
            for (int j = 0; j <= k; j++)
                next[j] = ch == 'I' ? prefix[j]
                                    : (ch == 'D' ? (prefix[k] - prefix[j] + mod) % mod : prefix[k]);
            dp.swap(next);
        }
        long long answer = 0;
        for (auto x : dp)
            answer = (answer + x) % mod;
        cout << answer << '\n';
    }
}

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

更多