DP 之 poj 3280

如欲有渐进的学习过程,请 点击打开此处链接
//  [4/4/2014 Sjm]
/*
状态: dp[i][j] := 从 i 位置到 j 位置构成回文串,所需要的最小开销
决策:
1) 若 str[i] == str[j], 则此时可获得 dp[i][j] 的一种情况,即 dp[i][j] = dp[i+1][j-1] 
2)若 str[i] != str[j] 或 str[i] == str[j] 皆可能有以下操作:
	1、可删除 str[i],此时可获得 dp[i][j] 的一种情况,即 dp[i][j] = dp[i+1][j] + mymap[str[i]].del_Value
	2、可在 j 的后面添加 str[i], 此时可获得 dp[i][j] 的一种情况,
		即 dp[i][j] = dp[i+1][j] + mymap[str[i]].add_Value
	与 1, 2 同,亦可对 str[j] 进行处理,故不再详述
*/
 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cstring>
 4 #include <algorithm>
 5 #include <climits>
 6 #include <map>
 7 using namespace std;
 8 const int MAX_N = 2000;
 9 int dp[MAX_N][MAX_N], N, mylen;
10 char str[MAX_N];
11 struct node
12 {
13     int add_Value, del_Value;
14 };
15 map<char, node> mymap;
16 
17 int Get_Min(int i, int j)
18 {
19     int temp = INT_MAX;
20     temp = min(temp, dp[i + 1][j] + min(mymap[str[i]].del_Value, mymap[str[i]].add_Value));
21     temp = min(temp, dp[i][j - 1] + min(mymap[str[j]].del_Value, mymap[str[j]].add_Value));
22     return temp;
23 }
24 
25 int Solve()
26 {
27     memset(dp, 0, sizeof(dp));
28     for (int t = 1; t < mylen; t++){
29         for (int i = 0; i < (mylen - t); i++) {
30             int j = i + t;
31             dp[i][j] = INT_MAX;
32             if (str[i] == str[j])
33                 dp[i][j] = min(dp[i][j], dp[i + 1][j - 1]);
34             dp[i][j] = min(dp[i][j], Get_Min(i, j));
35         }
36     }
37     return dp[0][mylen - 1];
38 }
39 
40 int main()
41 {
42     //freopen("input.txt", "r", stdin);
43     //freopen("output.txt", "w", stdout);
44     scanf("%d %d", &N, &mylen);
45     scanf("%s", str);
46     for (int i = 0; i < N; i++) {
47         char c;
48         int aValue, dValue;
49         cin >> c >> aValue >> dValue;
50         mymap[c].add_Value = aValue;
51         mymap[c].del_Value = dValue;
52     }
53     printf("%d\n", Solve());
54     return 0;
55 }

 



posted @ 2014-04-05 01:04  JmingS  阅读(191)  评论(0编辑  收藏  举报