LightOJ_1025The Specials Menu(區間DP)

1025 - The Specials Menu
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;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章