Time Limit: 2 second(s) | Memory Limit: 32 MB |
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 |
原题连接:http://www.lightoj.com/volume_showproblem.php?problem=1025
题意:求一个字符串删掉若干字母后能组成回文串的个数。
思路:区间DP(DP太菜,完全没想到。。。)dp[l][r]代表 l 到 r 区间内回文串的个数,
转移方程dp[l][r]=dp[l+1][r]+dp[l][r-1]。
#include<cstdio>
#include<iostream>
#include<cstring>
#include<cmath>
#include<cstdlib>
#include<algorithm>
#include<set>
#include<map>
#include<string>
#include<queue>
#include<stack>
#include<sstream>
#include<ctype.h>
#include<vector>
#include<list>
using namespace std;
typedef long long ll;
const int INF=1<<30;
const double eps=0.0000001;
const int maxn = 60+5;
ll dp[maxn][maxn]; //dp[l][r]代表区间l到r之间的回文串个数
int main()
{
int T;
scanf("%d",&T);
int cas=1;
while(T--)
{
char s[100];
memset(dp,0,sizeof(dp));
scanf("%s",s+1);
int len=strlen(s+1);
for(int i=1;i<=len;i++)
{
for(int l=1;l+i-1<=len;l++)
{
int r=l+i-1;
dp[l][r]+=dp[l+1][r];
dp[l][r]+=dp[l][r-1];
if(s[l]==s[r])
dp[l][r]++;
else
dp[l][r]-=dp[l+1][r-1];
}
}
printf("Case %d: %lld\n",cas++,dp[1][len]);
}
return 0;
}