poj 2127 LCIS 带路径输出
这个题 用一维 为什么错了; 因为 用一维 dp 方程肯定也是一维;但是有没有想,第 i 个字符更新了 j 位置的最优结果,然后 k 字符又一次更新了 j 位置的最优值,然后 我的结果是 i 字符更新的结果; 但被覆盖了 所以错了; 不如用一个二维数组 表示 地 i 个字符放进去匹配另一个字符的 j 位置的最优值是由那个位置传递过来的;
1 #include<iostream> 2 #include<stdio.h> 3 #include<algorithm> 4 #include<cstring> 5 #include<cmath> 6 #include<vector> 7 using namespace std; 8 9 vector<int>vv; 10 int num1[555],num2[555],dp[555][555]; 11 struct date{ int x,y; }path[555][555]; 12 void update( int x,int y ){ 13 if( !x || !y )return ; 14 update( path[x][y].x,path[x][y].y ); 15 if( num1[x] == num2[y] )cout<<num1[x]<<" "; 16 } 17 int main( ) 18 { 19 int N,M,T; 20 while( scanf("%d",&N) != EOF ) 21 { 22 for( int i = 1; i <= N; i++ )scanf("%d",&num1[i]); 23 scanf("%d",&M); 24 for( int i = 1; i <= M; i++ )scanf("%d",&num2[i]); 25 memset( dp,0,sizeof(dp) );vv.clear(); 26 memset( path,0,sizeof(path) ); 27 for( int i = 1; i <= N; i++ ) 28 { 29 int Max = 0; int pos = 0; 30 for( int j = 1; j <= M; j++ ) 31 { 32 if( num1[i] > num2[j] && dp[i-1][j] > Max ){ 33 Max = dp[i-1][j]; 34 pos = j; 35 } 36 if( num1[i] == num2[j] ){ 37 dp[i][j] = Max + 1 ; 38 path[i][j].x = i-1; path[i][j].y = pos; 39 }else { 40 dp[i][j] = dp[i-1][j]; 41 path[i][j].x = i-1; path[i][j].y = j; 42 } 43 } 44 } 45 int res = 0; 46 for( int i = 1; i <= M; i++ ) 47 if( dp[N][i] > res )res = dp[N][i]; 48 bool fell = false; cout<<res<<endl; 49 for( int i = 1; i <= M; i++ ) 50 if( dp[N][i] == res ) 51 { update( N,i ); break; } 52 } 53 return 0; 54 }