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.
题意:对于字符串S,可以从S中去掉任意字符,形成的字符串中有多少是回文串。
定义dp[i][j] 为区间i ~ j 中有多少回文串, 当(i == j)时,dp[i][j] = 1。
1)s[i] != s[j] , 那么dp[i][j]只能由 dp[i+1][j] 和 dp[i][j-1] 转移过来,而且要减去
重复区间dp[i+1][j-1]。
2)s[i] == s[j], dp[i][j] 除了由 (1)状态贡献之外,还要加上dp[i+1][j-1]贡献的。
/***********************************************
* Author: fisty
* Created Time: 2015-07-14 22:27:44
* File Name : 1025.cpp
*********************************************** */
#include <iostream>
#include <cstring>
#include <deque>
#include <cmath>
#include <queue>
#include <stack>
#include <list>
#include <map>
#include <set>
#include <string>
#include <vector>
#include <cstdio>
#include <bitset>
#include <algorithm>
using namespace std;
#define Debug(x) cout << #x << " " << x <<endl
#define Memset(x, a) memset(x, a, sizeof(x))
const int INF = 0x3f3f3f3f;
typedef long long LL;
typedef pair<int, int> P;
#define FOR(i, a, b) for(int i = a;i < b; i++)
#define MAX_N 65
int t;
string s;
LL dp[MAX_N][MAX_N];
int main() {
//freopen("in.cpp", "r", stdin);
cin.tie(0);
ios::sync_with_stdio(false);
cin >> t;
int cnt = 1;
while(t--){
cin >> s;
Memset(dp, 0);
int len = s.length();
for(int i = 0;i < len; i++){
dp[i][i] = 1;
}
for(int i = len-1;i >= 0; i--){
for(int j = i+1;j < len; j++){
if(s[i] != s[j]){
dp[i][j] = dp[i+1][j] + dp[i][j-1] - dp[i+1][j-1];
}else{
//dp[i][j] = (dp[i+1][j] + dp[i][j-1] - dp[i+1][j-1]) + (dp[i+1][j-1] + 1);
dp[i][j] = dp[i+1][j] + dp[i][j-1] + 1;
}
}
}
cout << "Case " << cnt++ << ": ";
cout << dp[0][len-1] << endl;
}
return 0;
}