a554中等回文表與最少切段前綴DP

CPE:Partitioning by Palindromes (UVa 11584)

先確認每個區間是否回文,再選最後一段的位置。

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

解題思路

回文判斷有重疊子問題:s[l..r] 是回文,若且唯若兩端字元相等,且長度不超過2或內層 s[l+1..r−1] 是回文。把 l 從右往左、r 從左往右填表,確保內層已算好。

定義 dp[i] 為前 i 個字元的最少回文段數,dp[0]=0。枚舉最後一段的起點 l,只要 s[l..i−1] 回文,就用 dp[l]+1 更新 dp[i]。每個合法切法都有唯一最後一段,所以轉移涵蓋全部可能,且每段非空。每筆輸出 dp[n]。

Step-by-step animation

示意:字串 aab

回報動畫錯誤
步驟 1 / 3

回文表

單字元都回文,aa 也回文,ab 與 aab 不是。

a:1
aa:1
aab:0
b:1
n
3

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;

int main() {
    int t;
    cin >> t;
    while (t--) {
        string s;
        cin >> s;
        int n = s.size();
        vector<vector<bool>> pal(n, vector<bool>(n));
        for (int l = n - 1; l >= 0; --l)
            for (int r = l; r < n; ++r)
                pal[l][r] = s[l] == s[r] && (r - l < 2 || pal[l + 1][r - 1]);
        vector<int> dp(n + 1, n + 1);
        dp[0] = 0;
        for (int end = 1; end <= n; ++end)
            for (int l = 0; l < end; ++l)
                if (pal[l][end - 1])
                    dp[end] = min(dp[end], dp[l] + 1);
        cout << dp[n] << '\n';
    }
}

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

更多