题目:Light OJ 1025 The Specials Menu
Feuzem is an unemployed computer scientist who spends his days working at odd-jobs. While on the job he always manages to find algorithmic problems within mundane aspects of everyday life.
Today, while writing down the specials menu at the restaurant he’s working at, he felt irritated by the lack of palindromes (strings which stay the same when reversed) on the menu. Feuzem is a big fan of palindromic problems, and started thinking about the number of ways he could remove letters from a particular word so that it would become a palindrome.
Two ways that differ due to order of removing letters are considered the same. And it can also be the case that no letters have to be removed to form a palindrome.
Input
Input starts with an integer T (≤ 200), denoting the number of test cases.
Each case contains a single word W (1 ≤ length(W) ≤ 60).
Output
For each case, print the case number and the total number of ways to remove letters from W such that it becomes a palindrome.
Sample Input
3
SALADS
PASTA
YUMMY
Sample Output
Case 1: 15
Case 2: 8
Case 3: 11
题意:
删去任意个字符,求构成回文串的总数。
分析:二维DP,找区间最优解。一开始想着枚举区间长度,起始位置和中间节点,进行区间合并,可是发现不对哦。只需要枚举区间长度和起始位置,直接状态转移,不涉及区间合并问题(区间之间相互有影响,那就不需要区间合并了),直接推方程:
dp[i][j];表示区间[i,j]的最大回文串数;
str[i] == str[j]:dp[i][j] = dp[i][j - 1] + dp[i + 1][j] - dp[i + 1][j - 1] + dp[i + 1][j - 1] + 1= dp[i][j - 1] + dp[i + 1][j] + 1;
str[i] != str[j]: dp[i][j] = dp[i][j - 1] + dp[i + 1][j] - dp[i + 1][j - 1];
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cmath>
using namespace std;
typedef long long LL;
const int MAXN = 65;
LL dp[MAXN][MAXN];
char str[MAXN];
int main() {
int T;
scanf("%d", &T);
while(T--) {
getchar();
memset(dp, 0, sizeof(dp));
scanf("%s", str + 1);
int n = strlen(str + 1);
for(int i = 1; i <= n; ++i) { //初始化长度为1的情况
dp[i][i] = 1;
}
for(int L = 2; L <= n; ++L) { //不涉及区间合并
for(int i = 1; i <= n - L + 1; ++i) {//枚举区间长度和起始位置
int j = i + L - 1;
if(str[i] == str[j])
dp[i][j] = dp[i][j - 1] + dp[i + 1][j] + 1LL;
else dp[i][j] = dp[i][j - 1] + dp[i + 1][j] - dp[i + 1][j - 1];
}
}
static int p = 1;
printf("Case %d: %lld\n", p++, dp[1][n]);
}
return 0;
}