题目链接:点击这里
题目大意:
给出两个字符串
s
,
t
s,t
s,t ,记
s
s
s 的子序列为
s
′
s'
s′ ,
t
t
t 的子序列为
t
′
t'
t′ ,求
m
a
x
(
∣
s
′
∣
+
∣
t
′
∣
)
max(|s'|+|t'|)
max(∣s′∣+∣t′∣)
题目分析:
看到答案跟二者子序列有关,就会很容易的联想到最长公共子序列,在
d
p
dp
dp 过程中维护答案即可
维护方式:
记
l
s
=
∣
s
∣
,
l
t
=
∣
t
∣
,
d
p
[
i
]
[
j
]
为
l
c
s
数
组
ls=|s|,lt=|t|,dp[i][j]为lcs数组
ls=∣s∣,lt=∣t∣,dp[i][j]为lcs数组
当
s
i
<
t
j
s_i < t_j
si<tj 时,可以取
d
p
[
i
−
1
]
[
j
−
1
]
dp[i-1][j-1]
dp[i−1][j−1] 作为前面相同的元素,因为
s
i
<
t
j
s_i < t_j
si<tj 了所以
s
i
s_i
si 和
t
j
t_j
tj 后面元素的选取就变成了任意的,因为要尽可能让子序列更长所以我们就把后面的全选上,于是此时
a
n
s
=
m
a
x
(
a
n
s
,
d
p
[
i
−
1
]
[
j
−
1
]
∗
2
+
l
s
−
i
+
1
+
l
t
−
j
+
1
)
ans = max(ans,dp[i-1][j-1]*2+ls-i+1+lt-j+1)
ans=max(ans,dp[i−1][j−1]∗2+ls−i+1+lt−j+1)
对于任意的
s
i
s_i
si 和
t
j
t_j
tj 都有
a
n
s
=
m
a
x
(
a
n
s
,
d
p
[
i
]
[
j
]
∗
2
+
l
t
−
j
)
ans = max(ans,dp[i][j]*2+lt-j)
ans=max(ans,dp[i][j]∗2+lt−j) ,因为空串的字典序是比任意串的字典序都小的
具体细节见代码:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<vector>
#define ll long long
#define inf 0x3f3f3f3f
using namespace std;
int read()
{
int res = 0,flag = 1;
char ch = getchar();
while(ch<'0' || ch>'9')
{
if(ch == '-') flag = -1;
ch = getchar();
}
while(ch>='0' && ch<='9')
{
res = (res<<3)+(res<<1)+(ch^48);//res*10+ch-'0';
ch = getchar();
}
return res*flag;
}
const int maxn = 2e3+5;
const int mod = 1e9+7;
const double pi = acos(-1);
const double eps = 1e-8;
char s[maxn],t[maxn];
int dp[maxn][maxn];
int main()
{
while(~scanf("%s%s",s+1,t+1))
{
int ls = strlen(s+1),lt = strlen(t+1),ans = 0;
memset(dp,0,sizeof(dp));
for(int i = 0;i <= ls;i++)
for(int j = 0;j <= lt;j++)
{
if(i && j)
{
dp[i][j] = max(dp[i-1][j],dp[i][j-1]);
if(s[i] == t[j]) dp[i][j] = max(dp[i][j],dp[i-1][j-1]+1);
else if(s[i] < t[j]) ans = max(ans,dp[i-1][j-1]*2+ls-i+1+lt-j+1);
}
ans = max(ans,dp[i][j]*2+lt-j);
}
printf("%d\n",ans);
}
return 0;
}