or palindrome
- describe
-
Determining a palindrome is easy, and turning a string into a palindrome is not difficult. Now let's increase the difficulty and give a string of characters ( all lowercase letters ) , adding or deleting a character will incur a certain cost. So what is the minimum cost to turn a string into a palindrome?
- enter
-
Multiple sets of data
The first one has two numbers n, m, which represent the number of characters and the length of the string respectively. The
second line gives a string of characters, and the next n lines, each line has a character (a~z) and Two integers, representing the cost of adding and removing this character, respectively,
all numbers are less than 2000 - output
- minimum cost
- sample input
-
3 4 abcb a 1000 1100 b 350 700 c 200 800
- Sample output
-
900
a | b | c | b | |
0 | 350 | 550 | 900 | |
0 | 200 | 0 | ||
0 | 200 | |||
0 |
The above picture is the result of my program running example. Now let's think deeply about what the interval of the interval dp represents. As far as this question is concerned, it represents the minimum cost from position i to position j, then it is not difficult for us to think of state transition. equation,
That is: when the values of the two positions are not equal dp[i][j] = (dp[i+1][j]+cost[v[i]])>(dp[i][j-1]+ cost[v[j]])?(dp[i][j-1]+cost[v[j]]):(dp[i+1][j]+cost[v[i]])
else dp[i][j] = min(dp[i][j],dp[i+1][j-1])
AC: code
#include<cstdio> #include<cstring> #include<iostream> #include<algorithm> using namespace std; const int maxn = 2001; int dp[maxn][maxn]; int cost[26]; int v[maxn]; int n,m; int get_min (int a, int b, int c, int d) { return min(min(a,b),min(c,d)); } intmain() { while(~scanf("%d %d",&m,&n)) { getchar(); char a; for(int i = 1;i<=n;i++) { scanf("%c",&a); v[i] = a - 'a'; } int b,c; for(int i = 0;i<m;i++){ getchar(); scanf("%c %d %d",&a,&b,&c); cost[a-'a'] = b>c?c:b; } //memset(dp,0,sizeof(dp)); for(int l = 1;l<=n;l++){ for(int i = 1;i+l-1<=n;i++){ int j = i + l-1; if(l == 1) dp[i][j] = 0; else { dp[i][j] = (dp[i+1][j]+cost[v[i]])>(dp[i][j-1]+cost[v[j]])?(dp[i][j-1]+cost[v[j]]):(dp[i+1][j]+cost[v[i]]); if(v[i] == v[j]) { dp[i][j] = min(dp[i][j],dp[i+1][j-1]); } } } } printf("%d\n",dp[1][n]); } return 0; }