题目链接
http://acm.hust.edu.cn/vjudge/problem/34398
题意
给定一个字符串,将其划分为若干个串,并且每个串都要是回文串,要求划分出来的回文串数目最小
思路
转移方程 d[i] = min(d[j] + 1) 其中s[j + 1] ~ s[i]要是回文串
其中状态O(n),转移O(n) 时间复杂度为O(n)。但是每次要判断s[j + 1] ~ s[i]是否为回文串,这样时间复杂度高达O(n^3)
因此,可现在O(n)的时间复杂度内预处理出j~i是否为回文串
代码
#include <iostream>
#include <cstring>
#include <stack>
#include <vector>
#include <set>
#include <map>
#include <cmath>
#include <queue>
#include <sstream>
#include <iomanip>
#include <fstream>
#include <cstdio>
#include <cstdlib>
#include <climits>
#include <deque>
#include <bitset>
#include <algorithm>
using namespace std;
#define PI acos(-1.0)
#define LL long long
#define PII pair<int, int>
#define PLL pair<LL, LL>
#define mp make_pair
#define IN freopen("in.txt", "r", stdin)
#define OUT freopen("out.txt", "wb", stdout)
#define scan(x) scanf("%d", &x)
#define scan2(x, y) scanf("%d%d", &x, &y)
#define scan3(x, y, z) scanf("%d%d%d", &x, &y, &z)
#define sqr(x) (x) * (x)
#define pr(x) cout << #x << " = " << x << endl
#define lc o << 1
#define rc o << 1 | 1
#define pl() cout << endl
#define CLR(a, x) memset(a, x, sizeof(a))
#define FILL(a, n, x) for (int i = 0; i < n; i++) a[i] = x
const int maxn = 3000 + 5;
const int INF = 0x3e3e3e3e;
char s1[maxn], s[maxn];
bool h[maxn][maxn];
int d[maxn];
int dp(int x) {
if (d[x] != -1) return d[x];
if (x < 0) return d[x] = 0;
d[x] = INF;
for (int i = -1; i < x; i++) {
if (h[i + 1][x]) {
//cout << i << ' ' << x << endl;
d[x] = min(d[x], dp(i) + 1);
}
}
return d[x];
}
int main() {
int T;
scan(T);
while (T--) {
memset(s, '\0', sizeof(s));
memset(s1, '\0', sizeof(s1));
scanf("%s", s1);
int len = strlen(s1);
for (int i = 0, j = 0; i < len; i++) {
s[j++] = s1[i];
s[j++] = '#';
}
len = strlen(s);
s[len - 1] = '\0';
len--;
CLR(h, 0);
for (int i = 0; i < len; i++) {
h[i][i] = 1;
int j = 1;
while (i - j >= 0 && i + j < len) {
int x = i - j, y = i + j;
if (s[x] == s[y]) {
if (!(x & 1) && !(y & 1)) h[x / 2][y / 2] = 1;
j++;
} else {
break;
}
}
}
int n = strlen(s1);
memset(d, -1, sizeof(d));
int ans = dp(n - 1);
printf("%d\n", ans);
}
return 0;
}