【算法竞赛入门经典】动态规划初步 例题9-7 UVa11584
例题UVa11584
Input
Input begins with the number n of test cases. Each test case consists of a single line of between 1 and 1000 lowercase letters, with no whitespace within.
Output
For each test case, output a line containing the minimum number of groups required to partition the input into groups of palindromes.
Sample Input
3
racecar
fastcar
aaadbccb
Sample Output
1
7
3
分析
利用dp[i]表示第1个字符到第i个字符最少的回文串数量。
这样,便利第0个到第i-1个字符,顺序记作j,这样,如果a[j]……a[i]构成回文串的话,那么dp[i]=dp[j]+1
这样遍历j取最小之后
dp[n]就是答案了
样例实现代码
#include<iostream>
#include<algorithm>
#include<string>
#include<cstring>
#define maxn 1000+5
#define INF 100000
using namespace std;
int dp[maxn], isp[maxn][maxn];
string a;
bool ispf(int i, int j) {
if (i >= j)
return true;
if (a[i] != a[j])
return false;
if (isp[i][j] >= 0)
return isp[i][j];
isp[i][j] = ispf(i + 1, j - 1);
return isp[i][j];
}
int main() {
int T;
cin >> T;
getchar();
while (T--) {
getline(cin, a);
int n = a.size();
a = " " + a;
memset(dp, 0, sizeof(dp));
memset(isp, -1, sizeof(isp));
for (int i = 1; i <= n; i++) {
dp[i] = dp[i - 1] + 1;
for (int j = 0; j<i; j++) {
if (ispf(j, i)) {
dp[i] = min(dp[i], dp[j-1] + 1);
}
}
}
cout << dp[n] << endl;
}
return 0;
}