poj3280 configured minimum cost string palindrome - interval dp

The meaning of problems

Thinking

dp [i] [j] is stored in this section i ~ j and the optimal solution has been palindromic

So when we ask new section i ~ j need only consider the s [i]? = S [j]

if(s[i] == s[j]) dp[i][j] = min(dp[i][j],dp[i +1][j - 1]);

else dp[i][j] = min(dp[[i][j],min(dp[i + 1][j] + chan[s[i]],dp[i][j - 1] + chan[s[j]]));

Each character array chan min (add, reduce), this is because when either side of s [i]! = time s [j] to the dp [i +1] [j] converted into one s [i] may be in the i discard bit or s [j] added something behind s [i] thus cost + = min (add, reduce) dp [i] [j - 1] is the same procedure

Each dp [i] [j] represents a palindrome optimal solution in this section is the direct successor of like no aftereffect will not affect the answer back

ACcode

#include<cstdio>
#include<iostream>
#include<cstring>
#include<string>

using namespace std;
const int inf = 0x3f3f3f3f;

int n,len;
char op;
char s[2005];
int ad[30],re[30],chan[30];
int dp[2005][2005];

int main()
{
	scanf("%d %d",&n,&len);
	scanf("%s",s + 1);
	s[0] = '#',s[len + 1] = '#';
	for(int i = 1;i <= n; i++){
		scanf(" %c",&op);
		int cur = op - 'a';
		scanf("%d %d",&ad[cur],&re[cur]);
		chan[cur] = min(ad[cur],re[cur]);
	}
	memset(dp,0,sizeof dp);
	for(int i = 1;i <= len; i++){
		for(int j = i;j <= len; j++) dp[i][j] = inf;
	}
	for(int L = 1;L <= len; L++){
		for(int i = 1;i + L - 1 <= len; i++){
			int j = i + L - 1;
			if(s[i] == s[j]) dp[i][j] = min(dp[i][j],dp[i + 1][j - 1]);
			else dp[i][j] = min(dp[i][j],min(dp[i + 1][j] + chan[s[i] - 'a'],dp[i][j - 1] + chan[s[j] - 'a']));
		}
	}
	printf("%d\n",dp[1][len]);
}

 

Published 31 original articles · won praise 5 · Views 1367

Guess you like

Origin blog.csdn.net/qq_43685900/article/details/102817275