标签:
1 /*
2 LCS裸题:长度减去最大相同长度就是要插入的个数
3 dp数组二维都开5000的话就会超内存,这里就用到了滚动数组,
4 因为在LCS的计算中,i的变化只相差1,所以可以通过对2取余来进行滚动:)
5 */
6 #include <cstdio>
7 #include <iostream>
8 #include <cstring>
9 #include <algorithm>
10 #include <string>
11 using namespace std;
12
13 const int MAXN = 5e3 + 10;
14 const int INF = 0x3f3f3f3f;
15 int dp[2][MAXN];
16 string s, ss;
17
18 int LCS(int n)
19 {
20 int x = 0;
21 for (int i=1; i<=n; ++i)
22 {
23 x = 1 - x;
24 for (int j=1; j<=n; ++j)
25 {
26 if (ss[i-1] == s[j-1])
27 {
28 dp[x][j] = dp[1-x][j-1] + 1;
29 }
30 else
31 {
32 dp[x][j] = max (dp[x][j-1], dp[1-x][j]);
33 }
34 }
35 }
36
37 return dp[x][n];
38 }
39
40 int main(void) //POJ 1159 Palindrome
41 {
42 #ifndef ONLINE_JUDGE
43 freopen ("1159.in", "r", stdin);
44 #endif
45
46 int n;
47 while (~scanf ("%d", &n))
48 {
49 memset (dp, 0, sizeof (dp));
50 cin >> ss;
51 s = ss;
52 reverse (s.begin (), s.end ());
53
54 int res = LCS (n);
55 printf ("%d\n", n - res);
56 }
57
58 return 0;
59 }
标签:
原文地址:http://www.cnblogs.com/Running-Time/p/4466946.html