Poj 1159 palindrome (string-to-text: LCs)
Http://poj.org/problem? Id = 1159
Question:
I will give you a string and ask you if you need to insert a few characters into the string, but it will become a return string.
Analysis:
First, match the original string with its inverse string to find the longest common subsequence. the string of the longest common subsequence must be a return string. therefore, the rest of the original string does not constitute a background. we only need to add the remaining part of the characters to the corresponding position, and the original string naturally becomes a background.
So the answer to this question is: N minus (the LCS length of the original string and the inverse string ).
For example, DP [I] [J] = X indicates the longest common subsequence of the first I character of string a and the first J character of string B.
Initialization: DP is all 0.
Status transfer:
A [I] = B [J]: DP [I] [J] = DP [I-1] [J-1] + 1.
A [I]! = B [J]: DP [I] [J] = max (DP [I-1] [J], DP [I] [J-1]).
Final requirement: DP [N] [M].
The two-dimensional rolling array used by the program. If int [5000] [5000] is used, the memory will be exceeded.
AC code:
#include<cstdio>#include<cstring>#include<algorithm>using namespace std;const int maxn=5000+5;int n;char s1[maxn],s2[maxn];int dp[2][maxn];int main(){ while(scanf("%d",&n)==1) { scanf("%s",s1); for(int i=0;i<n;i++) s2[i]=s1[n-1-i]; memset(dp,0,sizeof(dp)); for(int i=1;i<=n;i++) for(int j=1;j<=n;j++) { if(s1[i-1]==s2[j-1]) dp[i%2][j]=dp[(i-1)%2][j-1]+1; else dp[i%2][j]=max(dp[(i-1)%2][j] , dp[i%2][j-1]); } printf("%d\n",n-dp[n%2][n]); } return 0;}
Poj 1159 palindrome (string-to-text: LCs)