hdu 1503 DP

来源:互联网 发布:淘宝花呗还款有利息吗 编辑:程序博客网 时间:2024/04/30 12:48
/*分析:主要注意下是怎么递归输出的。求最长子串,然后碰到公共字母就输出公共字母,没碰到的话,先输a还是先输b都行。 */#include <iostream>#include <cstdio>#include <string>#include <cstring>using namespace std;char a[110], b[110];int dp[110][110], p[110][110];void f( int i, int j ){if( i == 0 && j == 0 ){return;}if( p[i][j] == 1 ){f( i-1, j-1 );cout << a[i-1];}else if( p[i][j] == 2 ){f( i-1, j );cout << a[i-1];} else{f( i, j-1 );cout << b[j-1];}}int main(){while( scanf( "%s%s", a, b ) != EOF ){int lengtha = strlen( a ), lengthb = strlen( b );memset( dp, 0, sizeof( dp ) );memset( p, 0, sizeof( p ) );for( int i = 0; i <= lengthb; i++ ){p[0][i] = 3;}for( int i = 0; i <= lengtha; i++ ){p[i][0] = 2;}for( int i = 1; i <= lengtha; i++ ){for( int j = 1; j <= lengthb; j++ ){if( a[i-1] == b[j-1]){dp[i][j] = dp[i-1][j-1] + 1;p[i][j] = 1;}else if( dp[i-1][j] > dp[i][j-1] ){dp[i][j] = dp[i-1][j];p[i][j] = 2;}else{dp[i][j] = dp[i][j-1];p[i][j] = 3;}}}f( lengtha, lengthb );cout << endl;}return 0;}

原创粉丝点击