Educational DP Contest F - LCS(最长公共子序列)
https://atcoder.jp/contests/dp/tasks/dp_f
题目大意:
给定字符串s和c(1<=s,c<=3000),求最长公共子序列的具体字符串。
Sample Input 1
axyb
abyxb
Sample Output 1
axb
正解:
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef pair<LL,LL> PII;
const LL MAXN=1e18;
const LL N=200200,M=3020;
LL f[M][M];
string mp[M][M];
int main()
{
cin.tie(0); cout.tie(0); ios::sync_with_stdio(false);
LL T=1;
//cin>>T;
while(T--)
{
string s,c;
cin>>s>>c;
LL n=s.size(),m=c.size();
s=" "+s;
c=" "+c;
for(int i=1;i<=n;i++)
{
for(int j=1;j<=m;j++)
{
f[i][j]=max(f[i-1][j],f[i][j-1]);
if(s[i]==c[j])
{
f[i][j]=max(f[i][j],f[i-1][j-1]+1);
}
}
}
//cout<<f[n][m]<<endl;
string ans="";
LL i=n,j=m;
while(i>0&&j>0)
{
if(s[i]==c[j])
{
ans+=s[i];
i--;
j--;
}
else
{
//直接找向更多更长相等字符串的位置
if(f[i-1][j]>f[i][j-1]) i--;
else j--;
}
}
//因为是倒着找的,所以我们需要对答案再倒一下
reverse(ans.begin(),ans.end());
cout<<ans<<endl;
}
return 0;
}
但是我不懂为啥这个写法会被t和re?
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef pair<LL,LL> PII;
const LL MAXN=1e18;
const LL N=200200,M=3020;
LL f[M][M];
string mp[M][M];
int main()
{
cin.tie(0); cout.tie(0); ios::sync_with_stdio(false);
LL T=1;
//cin>>T;
while(T--)
{
string s,c;
cin>>s>>c;
LL n=s.size(),m=c.size();
s=" "+s;
c=" "+c;
for(int i=1;i<=n;i++)
{
for(int j=1;j<=m;j++)
{
if(f[i-1][j]>f[i][j-1]) mp[i][j]=mp[i-1][j];
else mp[i][j]=mp[i][j-1];
f[i][j]=max(f[i-1][j],f[i][j-1]);
if(s[i]==c[j])
{
if(f[i-1][j-1]+1>f[i][j]) mp[i][j]=mp[i-1][j-1]+s[i];
f[i][j]=max(f[i][j],f[i-1][j-1]+1);
}
}
}
//cout<<f[n][m]<<endl;
cout<<mp[n][m]<<endl;
}
return 0;
}