1 #include <iostream> 2 #include <stack> 3 #define MAXN 150 4 #include <string> 5 6 using namespace std; 7 8 9 int dp[MAXN][MAXN]; 10 int mark[MAXN][MAXN]; 11 string s_1[MAXN]; 12 string s_2[MAXN]; 13 stack <string> coll; 14 15 int main() 16 { 17 int i; 18 int j; 19 string tem; 20 int n_1; 21 int n_2; 22 //freopen("acm.acm","r",stdin); 23 while(cin>>tem) 24 { 25 s_1[0] = tem; 26 i = 1; 27 while(cin>>tem) 28 { 29 if(tem == "#") 30 { 31 break; 32 } 33 s_1[i ++] = tem; 34 } 35 n_1 = i; 36 i = 0; 37 while(cin>>tem) 38 { 39 if(tem == "#") 40 { 41 break; 42 } 43 s_2[i ++] = tem; 44 } 45 n_2 = i; 46 dp[0][0] = 0; 47 for(i = 0; i <= n_1; ++ i) 48 { 49 dp[i][1] = 0; 50 } 51 for(i = 0; i <= n_2; ++ i) 52 { 53 dp[1][i] = 0; 54 } 55 memset(mark,-1,sizeof(mark)); 56 for(i = 0; i < n_1; ++ i) 57 { 58 for(j = 0; j < n_2; ++ j) 59 { 60 if(s_1[i] == s_2[j]) 61 { 62 dp[i+1][j+1] = dp[i][j] + 1; 63 mark[i][j] = 1; //相等来自i-1和j-1 64 } 65 else 66 { 67 if(dp[i+1][j] > dp[i][j+1]) 68 { 69 dp[i+1][j+1] = dp[i+1][j]; 70 mark[i][j] = 2; // j-1方向 71 } 72 else 73 { 74 dp[i+1][j+1] = dp[i][j+1]; 75 mark[i][j] = 3; // i-1方向 76 } 77 } 78 } 79 } 80 81 i = n_1-1; 82 j = n_2-1; 83 84 while(mark[i][j] != -1 && j >= 0 && i >= 0) 85 { 86 if(mark[i][j] == 1) 87 { 88 coll.push(s_1[i]); 89 -- i; 90 -- j; 91 } 92 else if(mark[i][j] == 2) 93 { 94 -- j; 95 } 96 else if(mark[i][j] == 3) 97 { 98 -- i; 99 } 100 } 101 102 103 while(!coll.empty()) 104 { 105 cout<<coll.top()<<" "; 106 coll.pop(); 107 } 108 cout<<endl; 109 } 110 111 }
时间: 2024-10-11 07:50:54