思路:
区间dp。添加和删除本质相同。
实现:
1 #include <iostream> 2 #include <cstdio> 3 using namespace std; 4 int n,m; 5 int cost[30]; 6 int dp[2005][2005]; 7 int main() 8 { 9 string s; 10 int x,y; 11 char z; 12 cin >> n >> m >> s; 13 for(int i = 0; i < n; i++) 14 { 15 cin >> z >> x >> y; 16 cost[z - 'a'] = min(x, y); 17 } 18 for(int i = m-1; i >= 0; i--) 19 { 20 for(int j = i+1; j < m; j++) 21 { 22 if(s[i] == s[j]) 23 { 24 dp[i][j] = dp[i+1][j-1]; 25 } 26 else 27 { 28 dp[i][j] = min(dp[i+1][j] + cost[s[i] - 'a'], 29 dp[i][j-1] + cost[s[j] - 'a']); 30 } 31 } 32 } 33 cout << dp[0][m-1] << endl; 34 return 0; 35 }