poj3280
将给定字符串用最小代价(添加,删除)变为回文串。
dp:dp[i][j]表示将i-j变为回文串的最小代价。
若s[i]==s[j],则dp[i][j]=dp[i+1][j-1]
否则,若s[i+1]--s[j]是回文串,则dp[i][j]=min(dp[i+1][j]+add[i],dp[i][j])
若s[i]--s[j-1]是回文串,则dp[i][j]=min(dp[i][j-1]+add[j],dp[i][j])
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#include<cstdio> #include<iostream> #include<cstdlib> #include<cstring> #include<cmath> #include<algorithm> using namespace std; char s[2100],ch; int n,m,a,b; int add[200],dp[2100][2100]; int main(){ scanf("%d%d",&n,&m); scanf("%s",s); for (int i=1;i<=n;i++){ cin>>ch; scanf("%d%d",&a,&b); add[ch]=min(a,b); } for (int k=1;k<m;k++) for (int i=0,j=k;j<m;i++,j++){ dp[i][j]=0x7fffffff; if (s[i]==s[j]) dp[i][j]=dp[i+1][j-1]; else{ dp[i][j]=min(dp[i+1][j]+add[s[i]],dp[i][j]); dp[i][j]=min(dp[i][j-1]+add[s[j]],dp[i][j]); } } printf("%d\n",dp[0][m-1]); return 0; }