回文字符串dp问题

1.Cheapest Palindrome(区间dp)

题目链接

d[i][j]:从ij为回文串花费的最小
状态转移方程:
if(s[i]==s[j])
d[i][j]=d[i+1][j-1]
else
d[i][j]=min(d[i][j-1]+add[s[j]],d[i+1][j]+add[s[i]],del[s[i]]+d[i+1][j],del[s[j]]+d[i][j-1])

#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N=2010;
int f[N][N];
int costa[30],costb[30];
int n,m;
string s;
void solve()
{
	for(int len=1;len<=m;len++)
	{
		for(int i=1;i+len-1<=m;i++)
		{
			int j=i+len-1;
			if(len==1)f[i][j]=0;
			else if(s[i]==s[j])
			{
				if(len==2)f[i][j]=0;
				else f[i][j]=f[i+1][j-1];
			}
			else 
			{
				int x=min(f[i][j-1]+costa[s[j]-'a'],f[i+1][j]+costa[s[i]-'a']);
				int y=min(costb[s[i]-'a']+f[i+1][j],costb[s[j]-'a']+f[i][j-1]);
				f[i][j]=min(x,y);
			}
		}
	}
	cout<<f[1][m]<<endl;
}
int main()
{
    memset(f,0x3f,sizeof f);
	cin>>n>>m;
    cin>>s;
    s=" "+s;
    for(int i=0;i<n;i++)
    {
    	char c;
    	cin>>c;
		int x,y;
    	cin>>x>>y;
    	costa[c-'a']=x;
    	costb[c-'a']=y;
	}
	solve();
	
}

2.Palindrome

题目链接
MLE做法:(类似于1的区间dp)
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N=5010;
int f[N][N];
int main()
{
    int n;
    string s;
    cin>>n;
    cin>>s;
    s=" "+s;
    for(int len=1;len<=n;len++)
    {
        for(int i=1;i+len-1<=n;i++)
        {
            int j=i+len-1;
            if(len==1)f[i][j]=0;
            else if(s[i]==s[j])
            {
                if(len==2)f[i][j]=0;
                else f[i][j]=f[i+1][j-1];
            }
            else
            {
                f[i][j]=min(f[i+1][j],f[i][j-1])+1;
            }
        }
    }
    cout<<f[1][n]<<endl;
}
AC做法

res=n-LCS

因为字符串和它的反向字符串的最大公共子序列的长度LCS,就等同于在原串中有LCS个字符是对应相等的。答案就是那些对应不相等的在对应位置添加相同的字符。所以res=n-LCS;

#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N=5010;
int f[2][N]={0};
int main()
{
	int n;
	cin>>n;
    string a,b;
    cin>>b;a=b;
    reverse(b.begin(),b.end());
    a=" "+a;
    b=" "+b;
    
    for(int i=1;i<=n;i++)
    {
    	for(int j=1;j<=n;j++)
    	{
    		f[i&1][j]=max(f[i-1&1][j],f[i&1][j-1]);
    		if(a[i]==b[j])
    		{
    			f[i&1][j]=max(f[i&1][j],f[i-1&1][j-1]+1);
			}
		}
	}
	cout<<n-f[n&1][n]<<endl;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

_WAWA鱼_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值