Light OJ 1025 The Specials Menu【区间DP】

题目:Light OJ 1025 The Specials Menu
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][j - 1] + dp[i + 1][j] - dp[i + 1][j - 1] + dp[i + 1][j - 1] + 1= dp[i][j - 1] + dp[i + 1][j] + 1;
str[i] != str[j]: dp[i][j] = dp[i][j - 1] + dp[i + 1][j] - dp[i + 1][j - 1];

#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cmath>
using namespace std;
typedef long long LL;

const int MAXN = 65;
LL dp[MAXN][MAXN];
char str[MAXN];

int main() {
    int T;
    scanf("%d", &T);
    while(T--) {
        getchar();
        memset(dp, 0, sizeof(dp));
        scanf("%s", str + 1);
        int n = strlen(str + 1);
        for(int i = 1; i <= n; ++i) { //初始化长度为1的情况
            dp[i][i] = 1;
        }
        for(int L = 2; L <= n; ++L) { //不涉及区间合并
            for(int i = 1; i <= n - L + 1; ++i) {//枚举区间长度和起始位置
                int j = i + L - 1;
                if(str[i] == str[j])
                    dp[i][j] = dp[i][j - 1] + dp[i + 1][j] + 1LL;
                else dp[i][j] = dp[i][j - 1] + dp[i + 1][j] - dp[i + 1][j - 1];
            }
        }
        static int p = 1;
        printf("Case %d: %lld\n", p++, dp[1][n]);
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值