poj 3267
dp问题,采用老办法,递归版本之后加记录。
1 #include <iostream> 2 #include <string> 3 #include <vector> 4 #include <cstdlib> 5 #include <cmath> 6 #include <map> 7 #include <algorithm> 8 #include <list> 9 #include <ctime> 10 #include <set> 11 #include <cstring> 12 #include <queue> 13 #include <cstdio> 14 #define CLR(arr, what) memset(arr, what, sizeof(arr)) 15 const int MAX = 100005; 16 const int maxc = 1500; 17 using namespace std; 18 string dict[602]; 19 int dp[302]; 20 int w, l; 21 string message; 22 int count(int pos, int wordnum) { 23 int i, res, j; 24 j = dict[wordnum].size() - 1; 25 for (i = pos; i >= 0; i--) { 26 if (message[i] == dict[wordnum][j]) { 27 j--; 28 } 29 if (j < 0) { 30 return i; 31 } 32 } 33 return -1; 34 } 35 int dfs(int cur) { 36 if (cur < 0) 37 return 0; 38 if (dp[cur] != -1) { 39 return dp[cur]; 40 } 41 int j, num_de, remain, szw; 42 int res = maxc; 43 for (int i = 0; i < w; i++) { 44 num_de = count(cur, i); 45 szw = dict[i].size(); 46 if (num_de >= 0) { 47 remain = dfs(num_de - 1); 48 res = min(res, cur - num_de + 1 - szw + remain); 49 } else { 50 remain = (cur + 1); 51 res = min(res, remain); 52 } 53 } 54 dp[cur] = res; 55 return res; 56 } 57 int main() { 58 while (scanf("%d%d", &w, &l) != EOF) { 59 cin >> message; 60 for (int i = 0; i < w; i++) { 61 cin >> dict[i]; 62 } 63 for (int i = 0; i < 302; i++) { 64 dp[i] = -1; 65 } 66 cout << dfs(l - 1) << endl; 67 } 68 return 0; 69 }