Palindrome DP
算法:
最长上升子序列,求字符串的正序和逆序的最长上升子序列,N - dp[N][N]就是最少要添加的单词。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#include<iostream> #include<string> using namespace std; class Matrix { public: int solve(int ); void input( ) { scanf("%s", pstr+1);} void reverse(int ); private: char pstr[5010]; char qstr[5010]; short int dp[5001][5001]; }M; void Matrix::reverse(int N) { for( int j = N, beg = 1; j >= 1; j--, beg++) qstr[beg] = pstr[j]; } int Matrix::solve(int N) { for( int i = 0; i <= N; i++) { dp[i][0] = 0; dp[0][i] = 0; } for( int i = 1; i <= N; i++) { for( int j = 1; j <= N; j++) { if( pstr[i] == qstr[j] ) dp[i][j] = dp[i-1][j-1] + 1; else dp[i][j] = max(dp[i-1][j], dp[i][j-1]); } } return N - dp[N][N]; } int main( ) { int N; while( scanf("%d",&N) != EOF ) { M.input( ); M.reverse( N ); printf("%d\n",M.solve(N)); } return 0; }
posted on 2012-09-15 10:41 more think, more gains 阅读(191) 评论(0) 编辑 收藏 举报