Uva 10617 Again Palindrome (区间DP+回文串)

本文介绍了如何使用区间动态规划方法解决UVA 10617题目,该题目要求计算从给定字符串中删除若干字符使其变为回文串的方案数。通过对多个测试用例的展示,解释了算法的输出结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Problem I

Again Palindromes

Input: Standard Input

Output: Standard Output

Time Limit: 2 Seconds

 

A palindorme is a sequence of one or more characters that reads the same from the left as it does from the right. For example,Z, TOT and MADAM are palindromes, butADAM is not.

 

Given a sequence S of N capital latin letters. How many ways can one score out a few symbols (maybe 0) that the rest of sequence become a palidrome. Varints that are only  different by an order of scoring out should be considered the same.

 

Input

The input file contains several test cases (less than 15). The first line contains an integerT that indicates how many test cases are to follow.

 

Each of the T lines contains a sequence S (1≤N≤60). So actually each of these lines is a test case.

 

Output

For each test case output in a single line an integer – the number of ways.

 

Sample Input   

3

BAOBAB

AAAA

ABA

Output for Sample Input

22

15

5

 
题意:给你一个串str(最长不超过60),问有多少种删去字符的方法使剩下的字符成为一个回文子串。
 
思路:dp[ i ][ j ]表示从第 i 个字符到第 j 个字符之间的回文串的数目。
 
当str[ i ]==str[ j ]的时候,要考虑i+1, j 组成的回文串,i ,j -1之间的回文串,但是两者都会计

算i+1,j-1的回文串数,所以要减去,另外,因为str[ i ]==str[ j ],所以i+1,j-1之间的回文串也能

和str[ i ],str[ j ]组成回文串,所以还要加上i+1,j-1之间的回文串。另外,str[ i ]与str[ j ]自身也

组成了回文串。
 
    即当 str[ i ] != str [ j ] 时         dp[ i ][ j ]  =  dp[ i+1 ][ j ] + dp[ i ][ j -1] - dp[ i+1 ][ j-1 ]  ;
 
             str[ i ] == str [ j ] 时         dp[ i ][ j ] =  dp[ i+1 ][ j ] + dp[ i ][ j -1] +1  ;
 
 
 
 
#include <iostream>
#include <string>
#include <cstdio>
#include <cstring>
using namespace std;
const int maxn=65;

string str;
long long dp[maxn][maxn];
int len;

void initial()
{
    for(int i=0; i<maxn; i++)
        for(int j=0; j<maxn; j++)
        {
            if(i==j)  dp[i][j]=1;
            else  dp[i][j]=0;
        }
}

void input()
{
    cin>>str;
    len=str.length();
}

void solve()
{
    for(int i=2; i<=len; i++)
        for(int j=0,k=i-1; k<len; j++,k++)
        {
                dp[j][k]=dp[j+1][k]+dp[j][k-1];
                if(str[j]==str[k])   dp[j][k]+=1;
                else  dp[j][k]-=dp[j+1][k-1];
        }
    printf("%lld\n",dp[0][len-1]);
}

int main()
{
    int T;
    scanf("%d",&T);
    while(T--)
    {
        initial();
        input();
        solve();
    }
    return 0;
}

 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值