一个由小写字母组成的字符串,划分成尽量少的回文串。
感觉和最长上升子序列差不多,区间dp,方法不对,导致TLE了好久。
dp[ R ] = min(dp[ R ], dp[ L - 1 ] + 1)( L <= R, ch[ L ][ R ] 是回文);
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
const int MAXN = 1000 + 10;
int dp[MAXN];
char ch[MAXN];
bool isPalind(int L, int R) //判断ch[L]...ch[R]是否回文
{
while (L < R)
{
if (ch[L] != ch[R]) return false;
L++;
R--;
}
return true;
}
int main()
{
int n;
scanf("%d", &n);
while (n--)
{
scanf("%s", ch + 1); //下标从1开始
int Len = strlen(ch + 1);
dp[0] = 0;
for (int R = 1; R <= Len; R++)
{
dp[R] = R; //初始化
for (int L = 1; L <= R; L++)
{
if (isPalind(L, R)) //状态转移
dp[R] = min(dp[R], dp[L - 1] + 1);
}
}
printf("%d\n", dp[Len]);
}
return 0;
}