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
Output for Sample Input
3
SALADS
PASTA
YUMMY
Case 1: 15
Case 2: 8
Case 3: 11
去掉任意字符找个回文串…
标准的区间dp
从左到右-1和从右到左-1加上减掉中间
如果两边一样就加上中间再+1
#include<iostream>
#include<cmath>
#include<cstdio>
#include<algorithm>
#include<string>
#include<memory.h>
using namespace std;
long long dp[61][61];
int main()
{
int T;
cin >> T;
int u = 0;
string q;
while (T--)
{
memset(dp, 0, sizeof(dp));
cin >> q;
int chang = q.size();
for (int a = 0;a < chang;a++)dp[a][a] = 1;
for (int a = 0;a < chang;a++)
{
for (int b = a-1;b >=0;b--)
{
dp[b][a] = dp[b][a - 1] + dp[b + 1][a] - dp[b + 1][a - 1];
if (q[a] == q[b])dp[b][a] += dp[b + 1][a - 1] + 1;
}
}
printf("Case %d: %lld\n", ++u, dp[0][chang - 1]);
}
return 0;
}

本文介绍了一个有趣的问题:如何从给定单词中移除部分字母使其成为回文串,并计算所有可能的方法数量。通过动态规划算法解决该问题,给出具体实现代码。
294

被折叠的 条评论
为什么被折叠?



