light oj 1025 - The 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



注意不删除如果是字符串也是一种方法;

题目大意:一串字符, 通过删除其中一些字符, 能够使这串字符变成回文串。 现在给你一串字符,问能够得到多少种不同的回文串;

注意:字符串"abba", 可以得到9串回文串,分别为'a', 'a', 'b', 'b', 'aa', 'bb', 'aba', 'aba', 'abba'.

解题思路:声明dp[i][j]为字符串[i,j]区间中通过删除可以得到不同回文串的数量

那么有以下两种情况:

1:当str[i] != str[j]时, dp[i][j] = dp[i][j-1] + dp[i+1][j] - dp[i+1][j-1]; (之所以减去dp[i+1][j-1] 是前面两项多加了一个dp[i+1][j-1])

2:当str[i] == str[j]时, dp[i][j] = (dp[i][j-1] + dp[i+1][j] - dp[i+1][j-1]) + (dp[i+1][j-1] + 1);(前面一项是指str[i]和str[j]不对应时能够组成回文串的方案数,第二项是指str[i]和str[j]对应时能够组成回文串的方案数)


#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;
const int N = 100;
long long  dp[N][N];
char str[N];


int main()
{
    int t, ncase=1;
    scanf("%d", &t);
    while(t--)
    {
        memset(dp,0,sizeof(dp));
        scanf("%s",str);
        int len=strlen(str);
        for(int i=0; i<len; i++)
            dp[i][i]=1;
        for(int l=1; l<len; l++)
        {
            for(int i=0; i<len-l; i++)
            {
                int j=i+l;
                if(str[i]!=str[j])
                    dp[i][j]=dp[i][j-1]+dp[i+1][j]-dp[i+1][j-1];
                else
                    dp[i][j]=dp[i][j-1]+dp[i+1][j]+1;中间的方法数加上俩边不删除中间的方法数加上,中间删除俩边不删;
            }
        }
        printf("Case %d: %lld\n",ncase++,dp[0][len-1]);
    }
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值