LCS
Problem Statement
You are given strings ss and tt. Find one longest string that is a subsequence of both ss and tt.
Notes
字符串的子序列是通过从中删除零个或多个字符并连接其余字符而不更改顺序而获得的字符串。xxxx
Constraints
- ss and tt are strings consisting of lowercase English letters.
- 1 \leq |s|, |t| \leq 30001≤∣s∣,∣t∣≤3000
Input
Input is given from Standard Input in the following format:
ss
tt
Output
Print one longest string that is a subsequence of both ss and tt. If there are multiple such strings, any of them will be accepted.
Sample 1
Inputcopy | Outputcopy |
---|---|
axyb abyxb | axb |
The answer is axb
or ayb
; either will be accepted.
Sample 2
Inputcopy | Outputcopy |
---|---|
aa xayaz | aa |
Sample 3
Inputcopy | Outputcopy |
---|---|
a z |
The answer is (an empty string).
Sample 4
Inputcopy | Outputcopy |
---|---|
abracadabra avadakedavra | aaadara |
#include <iostream>
#include <cstring>
#include <cmath>
using namespace std;
int p[3005][3005];
char s[3005],t[3005];
int main()
{
cin>>s>>t;
int ls=strlen(s)+2;
int lt=strlen(t)+2;
memset(p,0,sizeof p);
int fag=1;
for(int i=2;i<lt;i++)
{
for(int j=2;j<ls;j++)
{
if(t[i-2]==s[j-2])
{
p[i][j]=p[i-1][j-1]+1;
}
else
{
p[i][j]=max(p[i-1][j],p[i][j-1]);
}
// cout<<p[i][j]<<" ";
}
//cout<<endl;
}
char ans[3005];
int k;
k=p[lt-1][ls-1];
int i=lt-1;
int j=ls-1;
while(k>0)
{
if(p[i][j]==p[i-1][j])
{
i--;
}
else if(p[i][j]==p[i][j-1])
{
j--;
}
else
{
ans[k]=s[j-2];
// cout<<ans[k];
i--;j--;k--;
}
}
for(i=1;i<=p[lt-1][ls-1];i++)
{
cout<<ans[i];
}
return 0;
}