LCS POJ 1159 Palindrome

 

题目传送门

 1 /*  2  LCS裸题:长度减去最大相同长度就是要插入的个数  3 */  4 #include <cstdio>  5 #include <iostream>  6 #include <cstring>  7 #include <algorithm>  8 #include <string>  9 using namespace std; 10 11 const int MAXN = 5e3 + 10; 12 const int INF = 0x3f3f3f3f; 13 int dp[2][MAXN]; 14 string s, ss; 15 16 int LCS(int n) 17 { 18 int x = 0; 19 for (int i=1; i<=n; ++i) 20  { 21 x = 1 - x; 22 for (int j=1; j<=n; ++j) 23  { 24 if (ss[i-1] == s[j-1]) 25  { 26 dp[x][j] = dp[1-x][j-1] + 1; 27  } 28 else 29  { 30 dp[x][j] = max (dp[x][j-1], dp[1-x][j]); 31  } 32  } 33  } 34 35 return dp[x][n]; 36 } 37 38 int main(void) //POJ 1159 Palindrome 39 { 40  #ifndef ONLINE_JUDGE 41 freopen ("1159.in", "r", stdin); 42 #endif 43 44 int n; 45 while (~scanf ("%d", &n)) 46  { 47 memset (dp, 0, sizeof (dp)); 48 cin >> ss; 49 s = ss; 50  reverse (s.begin (), s.end ()); 51 52 int res = LCS (n); 53 printf ("%d\n", n - res); 54  } 55 56 return 0; 57 }

 

你可能感兴趣的:(poj)