設(shè)w[i,j]為i-j能分割成的最少回文串
f[i]為前i個字符能夠分成的最少回文串
w[i,j]=1 當(dāng)w[i+1,j-1]==1 && s[i]==s[j] 或 i==j-1 && s[i]==s[j]
w[i,j]=w[i+1,j-1]+2 當(dāng)s[i]!=s[j]
然后
f[i]=min{f[j]+w[j+1,i], 0<=j<i}
f[0]=0
題目白書有
#include <cstdio>
#include <cstring>
#include <cmath>
#include <string>
#include <iostream>
#include <algorithm>
#include <queue>
#include <set>
#include <map>
using namespace std;
typedef long long ll;
#define pii pair<int, int>
#define mkpii make_pair<int, int>
#define pdi pair<double, int>
#define mkpdi make_pair<double, int>
#define pli pair<ll, int>
#define mkpli make_pair<ll, int>
#define rep(i, n) for(int i=0; i<(n); ++i)
#define for1(i,a,n) for(int i=(a);i<=(n);++i)
#define for2(i,a,n) for(int i=(a);i<(n);++i)
#define for3(i,a,n) for(int i=(a);i>=(n);--i)
#define for4(i,a,n) for(int i=(a);i>(n);--i)
#define CC(i,a) memset(i,a,sizeof(i))
#define read(a) a=getint()
#define print(a) printf("%d", a)
#define dbg(x) cout << (#x) << " = " << (x) << endl
#define error(x) (!(x)?puts("error"):0)
#define printarr2(a, b, c) for1(_, 1, b) { for1(__, 1, c) cout << a[_][__]; cout << endl; }
#define printarr1(a, b) for1(_, 1, b) cout << a[_] << '\t'; cout << endl
inline const int getint() { int r=0, k=1; char c=getchar(); for(; c<'0'||c>'9'; c=getchar()) if(c=='-') k=-1; for(; c>='0'&&c<='9'; c=getchar()) r=r*10+c-'0'; return k*r; }
inline const int max(const int &a, const int &b) { return a>b?a:b; }
inline const int min(const int &a, const int &b) { return a<b?a:b; }
const int N=1005;
int n, f[N], w[N][N];
char s[N];
int main() {
int cs=getint();
while(cs--) {
scanf("%s", s+1);
n=strlen(s+1);
CC(f, 0x3f); CC(w, 0); f[0]=0;
for1(i, 1, n) w[i][i]=1;
for1(k, 1, n-1)
for1(i, 1, n-k) {
int j=i+k;
if(k==1 && s[i]==s[j]) w[i][j]=1;
else if(k>1 && w[i+1][j-1]==1 && s[i]==s[j]) w[i][j]=1;
else w[i][j]=w[i+1][j-1]+2;
}
for1(i, 1, n) rep(j, i) f[i]=min(f[i], f[j]+w[j+1][i]);
printf("%d\n", f[n]);
}
return 0;
}
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061
微信掃一掃加我為好友
QQ號聯(lián)系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長非常感激您!手機(jī)微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元

