Hdu 4745 Longest palindrome subsequence

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.