[记忆搜索_DP]http://222.200.98.145:8000/JudgeOnline/showproblem?problem_id=1065
题意: 给一个字符串,求出最长的对称字符串,输出其长度, 这里的对称与一般的palindrome不同,这里允许跳跃.
如给一个字符串: "aferegga", 最长的palindrome是"aerea"而不是"ere".
很容易找出解:
ans[f+1][t-1]+2, string[f]=string[t].
ans[f][t]= 0, f>t.
1, f=t.
max{ans[f][t-1],ans[f+1][t], string[f]!=string[t].
枚举必定超时, 要用到状态记忆.
1 #include < iostream >
2 #include < cstdio >
3 #include < string >
4 #include < cstring >
5 #include < vector >
6 #include < algorithm >
7
8 using namespace std;
9
10 const int MAXN = 1005 ;
11
12 int Ans[MAXN][MAXN];
13 char Str[MAXN];
14 inline int max( const int a, const int b)
15 {
16 return a < b ? b:a;
17 }
18
19 int get_max( int f, int t)
20 {
21 if ( f > t )
22 return 0 ;
23 if ( Ans[f][t] )
24 return Ans[f][t];
25 if ( f == t )
26 return Ans[f][t] = 1 ;
27 if ( Str[f] == Str[t] )
28 return Ans[f][t] = get_max(f + 1 , t - 1 ) + 2 ;
29 else
30 return Ans[f][t] = max(get_max(f + 1 ,t),get_max(f,t - 1 ));
31 }
32
33 int main()
34 {
35 freopen( " in " , " r " , stdin);
36 freopen( " out " , " w " , stdout);
37 while ( scanf( " %s " , Str) != EOF )
38 {
39 memset(Ans, 0 , sizeof (Ans));
40 printf( " %d\n " , get_max( 0 , strlen(Str) - 1 ));
41 }
42 return 0 ;
43 }
44