UVA 11584 Partitioning by Palindromes——dp
原创
©著作权归作者所有:来自51CTO博客作者软糖酱八号机的原创作品,请联系作者获取转载授权,否则将追究法律责任
n^2预处理一下a【i】【j】是否为回文串,处理的方法比较笨,分奇偶写的。。。
剩下的dp思路很好想,不多说了
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int maxn = 1010;
const int INF = 0x3f3f3f3f;
int T, n;
char s[maxn];
bool a[maxn][maxn];
int dp[maxn];
int main() {
scanf("%d", &T);
getchar();
while (T--) {
gets(s+1);
n = strlen(s+1);
memset(a, false, sizeof(a));
for (int i = 1; i <= n; i++) a[i][i] = true;
for (int i = 2; i < n; i++) {
int x = i - 1, y = i + 1;
while (x >= 1 && y <= n && s[x] == s[y]) {
a[x][y] = true;
x--; y++;
}
}
for (int i = 1; i <= n; i++) {
int x = i, y = i+1;
while (x >= 1 && y <= n && s[x] == s[y]) {
a[x][y] = true;
x--; y++;
}
}
dp[0] = 0;
for (int i = 1; i <= n; i++) {
dp[i] = i;
for (int j = 0; j < i; j++) {
if (a[j+1][i]) dp[i] = min(dp[i], dp[j] + 1);
}
}
printf("%d\n", dp[n]);
}
return 0;
}