Advanced Fruits-HDU1503
#include<bits/stdc++.h>
using namespace std;
#define IOS ios::sync_with_stdio(false),cin.tie(0),cout.tie(0)
#define int long long
#define pii pair<int,int>
string s1,s2,s; //输入的两个字符串和结果
int l1,l2; //s1,s2的长度
int dp[105][105]; //存储状态
stack<pii> sta; //存储最长公共子序列的下标,first代表s1的下标,second代表s2的下标
void solve(){
l1 = s1.length(),l2 = s2.length();
s1 = " " + s1,s2 = " "+ s2,s = "";
//初始化
for(int i = 1;i <= l1;++i)
for(int j = 1;j <= l2;++j)
if(s1[i] == s2[j])
dp[i][j] = dp[i - 1][j - 1] + 1;
else
dp[i][j] = max(dp[i][j - 1],dp[i - 1][j]);
//dp
int x = l1,y = l2;
while(x >= 1 && y >= 1){
if(s1[x] == s2[y])
sta.push(pii(x,y)),--x,--y;
else if(dp[x - 1][y] >= dp[x][y - 1])
--x;
else
--y;
}
//找到最长公共子序列的下标并且存入sta
pii from,to;from.first = 1,from.second = 1;
while(!sta.empty()){
to = sta.top(),sta.pop();
s += s1.substr(from.first,to.first - from.first)
+ s2.substr(from.second,to.second - from.second)
+ s1[to.first];
//将最长公共子序列的一个字母的前面部分都加上,并且加上一个一个字母
//如acbd和bcd其中最长公共子序列可以为cd
//那么第一步处理字母c之前的,我们s += 'a' += 'b' += 'c'
//第二步处理c之后d之前的
from.first = to.first + 1,from.second = to.second + 1;
}
s += s1.substr(from.first,l1 + 1 - from.first)
+ s2.substr(from.second,l2 + 1 - from.second);
//处理上述例子中d之后的
cout<<s<<"\n";
}
signed main(){
IOS;
while(cin>>s1>>s2)
solve();
return 0;
}