1.Cheapest Palindrome(区间dp)
题目链接
d[i][j]
:从i
到j
为回文串花费的最小
状态转移方程:
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;
}