Codeforces 245H 回文 DP

本文详细介绍了如何通过状态转移方程来计算字符串中回文子串的数量,包括初始化、回文子串判断及动态规划求解过程。此方法为解决字符串处理问题提供了一种高效策略。

                  看了解题报告才弄清楚状态转移方程:

Let isPal[i][j] be 1 if s[i...j] is palindrome, otherwise, set it 0. Let's define dp[i][j] to be number of palindrome substrings of s[i...j]. Let's calculate isPal[i][j] and dp[i][j] in O(|S|2). First, initialize isPal[i][i] = 1 and dp[i][i] = 1. After that, loop over len which states length of substring and for each specific len, loop over start which states starting position of substring. isPal[start][start + len - 1]can be easily calculated by the following formula:

isPal[start][start+len-1] = isPal[start+1][start+len-2] & (s[start] == s[start+len-1])

After that, dp[start][start + len - 1] can be calculated by the following formula which is derived from Inc-Exc Principle.

dp[start][start+len-1] = dp[start][start+len-2] + dp[start+1][start+len-1] - dp[start+1][start+len-2] + isPal[start][start+len-1]

        

#include<cstdio>
#include<iostream>
#include<cstring>
#define MAXN 5001
using namespace std;
int f[MAXN][MAXN],d[MAXN][MAXN];
int main()
{
   // freopen("in.txt","r",stdin);
    char str[MAXN];
    cin>>str;
    int len=strlen(str);
    memset(f,0,sizeof(f));
    memset(d,0,sizeof(d));
    for(int i=len-1;i>=0;i--)
    {
        f[i][i]=1;
        f[i][i-1]=1;
        for(int j=i+1;j<len;j++)
        {
            if(str[j]==str[i]&&f[i+1][j-1])
                f[i][j]=1;
        }
    }
    for(int i=len-1;i>=0;i--)
    {
        d[i][i]=1;
        for(int j=i+1;j<len;j++)
        {
            d[i][j]=d[i+1][j]+d[i][j-1]-d[i+1][j-1];
            if(f[i][j])
                d[i][j]++;
        }
    }
    int n,a,b;
    cin>>n;
    while(n--)
    {
        cin>>a>>b;
        cout<<d[a-1][b-1]<<endl;
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值