【动态规划】[UVa11584]Partitioning by Palindromes
我们令
#include <cstdio>
#include <algorithm>
#include <iostream>
#include <cstring>
using namespace std;
const int MAXN = 1000;
const int INF = 100000000;
char tmp[MAXN+10];
bool isback[MAXN+10][MAXN+10];
int dp[MAXN+10];
void solve(){
int len = strlen(tmp+1);
//printf("%d\n", len);
for(int i=1;i<=len;i++){
for(int j=0;;j++){
if(i-j < 1 || i+j > len) break;
if(tmp[i-j] != tmp[i+j]) break;
isback[i-j][i+j] = true;
}
}
int l, r;
for(int i=1;i<len;i++){
l = i, r = i+1;
while(l > 0 && r <= len){
if(tmp[l]!=tmp[r]) break;
isback[l][r] = true;
l--; r++;
}
}
}
int main(){
int n;
scanf("%d", &n);
while(n--){
memset(dp, 0, sizeof dp);
memset(isback, 0, sizeof isback);
scanf("%s", tmp+1);
int len = strlen(tmp+1);
solve();
for(int i=1;i<=len;i++){
dp[i] = isback[1][i]?1:i;
for(int j=1;j<i;j++){
if(isback[j+1][i])
dp[i] = min(dp[i], dp[j]+1);
}
}
printf("%d\n", dp[len]);
}
return 0;
}