您的位置:首页 > 其它

Light OJ 1025 The Specials Menu(区间DP)

2015-06-13 00:03 197 查看
Description

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+1][j-1]+1,因为考虑删除i+1~j-1之后str[i]和str[j]还是回文的。而且

str[i]和str[j]组成的回文+(i+1,j-1)中的回文组成的还是回文的。

其他的:考虑i和j的位置dp[i][j]+=dp[i+1][j]+dp[i][j-1]-dp[i+1][j-1],为不考虑str[i]或str[j]的方案数。

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<vector>
#include<string>
#include<iostream>
#include<queue>
#include<cmath>
#include<map>
#include<stack>
#include<bitset>
using namespace std;
#define REPF( i , a , b ) for ( int i = a ; i <= b ; ++ i )
#define REP( i , n )  for( int i = 0 ; i < n ; ++ i )
#define CLEAR( a , x ) memset ( a , x , sizeof a )
typedef long long LL;
const int mod = 1000000007;
char str[110];
int t;
LL dp[110][110];
int main()
{
    int cas=1;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%s",str+1);
        int len=strlen(str+1);
        CLEAR(dp,0);
        for(int i=1;i<=len;i++)
            dp[i][i]=1;
        for(int i=len-1;i>=1;i--)
            for(int j=i+1;j<=len;j++)
            {
                dp[i][j]+=dp[i+1][j]+dp[i][j-1]-dp[i+1][j-1];
                if(str[i]==str[j]) dp[i][j]+=dp[i+1][j-1]+1;
            }
        printf("Case %d: %lld\n",cas++,dp[1][len]);
    }
    return 0;									
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: