题意:输入一个由小写字母组成的字符串,你的任务是把它划分成尽量少的回文串。例如,racecar本身就是回文串;fastcar只能分成7个单字母的回文串,aaadbccb最少分成3个回文串:aaa,d,bccd。字符串长度不超过1000。(本段摘自《算法竞赛入门经典(第2版)》)
分析:
设dp[i]为到第i个位置为止,最少的划分次数,dp[i] = min(dp[j] + 1 && s[j + 1~i]是回文串)。
代码:
#include <iostream>
#include <algorithm>
#include <fstream>
#include <string>
#include <cstring>
#include <vector>
#include <queue>
#include <cmath>
#include <cctype>
#include <stack>
#include <set>
using namespace std;
const int maxn = 1000 + 5, INF = 1e9;
int T, l, tmp;
int dp[maxn];
char s[maxn];
bool judge(int x, int y)
{
for (int i = x, j = y; i < j; ++i, --j)
if (s[i] != s[j])
return false;
return true;
}
int main()
{
scanf("%d", &T);
for (int C = 0; C < T; ++C)
{
scanf("%s", s + 1);
l = strlen(s + 1);
dp[0] = 0;
for (int i = 1; i <= l; ++i)
{
tmp = INF;
for (int j = 0; j < i; ++j)
if (judge(j + 1, i))
tmp = min(tmp, dp[j] + 1);
dp[i] = tmp;
}
printf("%d\n", dp[l]);
}
return 0;
}