For any string, if the head and tail are the same, then its longest palindrome sequence must be the longest palindrome sequence of the part after the head-to-tail, plus the head and tail. If the head and tail are different, then its longest palindrome sequence is the longer that of the longest palindrome sequence that goes to the part of the head and the longest palindrome sequence of the part that goes to the tail. Set the string to S,f (I,J) to represent S[i: The longest palindrome subsequence of J]. The state transfer equation is as follows: When I>j, f (i,j) = 0. When I=j, f (i,j) = 1. When I<j and S[i]=s[j], F (i,j) =f (i+1,j-1) +2. When I<j and S[i]≠s[j], F (i,j) =max (f (i,j-1), F (i+1,j)). Note If I+1=j and S[i]=s[j], F (i,j) =f (i+1,j-1) +2=f (j,j-1) +2=2, this is the benefit of "F (i>j) i,j when =0". Since f (i,j) relies on i+1, the first dimension must be computed backwards, from s.length ()-1 to 0, when the loop is computed. Finally, the length of the longest palindrome subsequence of S is f (0, S.length ()-1).
I have to deal with this problem because it is a ring.
#include <stdio.h> #include <string.h> #include <iostream>using namespaceStd; int Dp[ .][ .]; int Max (int A ,int B ) { return A>B?A:B;} int Main () { int N,I,J; int Num[2100]; while (~scanf("%d",&N),N ) { for( I=1;I<=N;I++) {scanf("%d",&Num[I]);Num[I+N]=Num[I]; }Memset(Dp,0 ,sizeof( Dp)); int Max=0; for (I=N;I>=1;I--) {Dp[I][I]=1; for (J=I+1;J<=N;J + +) { if( Num[I]==Num[J])Dp[I][J]=Dp[I+1][J-1]+2; Else Dp[I][J]=Max(Dp[I+1][J],Dp[I][J-1]); }} for ( I=1;I<=N;I++) if (Dp[1][I]+Dp[I+1][N]>Max)Max=Dp[1][I]+Dp[I+1][N];Printf("%d\n",Max); } return 0;}
Hdu 4745 Longest palindrome subsequence