lightoj 1025 弱智区间dp

本文介绍了一个有趣的问题:如何从给定单词中移除部分字母使其成为回文串,并计算所有可能的方法数量。通过动态规划算法解决该问题,给出具体实现代码。

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

去掉任意字符找个回文串…
标准的区间dp
从左到右-1和从右到左-1加上减掉中间
如果两边一样就加上中间再+1

#include<iostream>
#include<cmath>
#include<cstdio>
#include<algorithm>
#include<string>
#include<memory.h>
using namespace std;
long long dp[61][61];
int main()
{
    int T;
    cin >> T;
    int u = 0;
    string q;
    while (T--)
    {
        memset(dp, 0, sizeof(dp));
        cin >> q;
        int chang = q.size();
        for (int a = 0;a < chang;a++)dp[a][a] = 1;
        for (int a = 0;a < chang;a++)
        {
            for (int b = a-1;b >=0;b--)
            {
                dp[b][a] = dp[b][a - 1] + dp[b + 1][a] - dp[b + 1][a - 1];
                if (q[a] == q[b])dp[b][a] += dp[b + 1][a - 1] + 1;
            }
        }
        printf("Case %d: %lld\n", ++u, dp[0][chang - 1]);
    }
    return 0;
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值