Description
Input
Output
思路:
首先我们要发现一个性质:
如果有
[
x
1
,
y
1
]
,
[
x
2
,
y
2
]
[x_1,y_1],[x_2,y_2]
[x1,y1],[x2,y2]两个区间,
而且
x
2
⩽
y
1
x_2\leqslant y_1
x2⩽y1 ,
那它就相当于
[
min
{
x
1
,
x
2
}
,
max
{
y
1
,
y
2
}
]
[\min\{x_1,x_2\},\max\{y_1,y_2\}]
[min{x1,x2},max{y1,y2}]这样的区间。
(因为你操作可以无限次)
接着枚举T的第i区间与S的第j个位置向左右两边最多可匹配个数。
这里考虑用双指针分别从j向左右两边匹配。记录l[i][j]表示S在j位置,
T用第i个区间向左匹配的最大值,r[i][j]则是向右边的。
最后=枚举最长公共子串左边可整块匹配的的位置,
不断向右边记忆化搜素知道右边不可以整块匹配,
再处理出两边不可整块匹配的个数,max取最大值。
#include <cstdio>
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 2e3 + 10;
struct node
{
int l, r;
} a[N * 50], nw[N];
char T[N], S[N];
int tn, sn, n, k, nn, nl[N], nr[N], num[N][30], r[N][N], l[N][N], f[N][N], ans;
bool cmp(node x, node y) {return x.l < y.l;}
int work(int x, int y)
{
if(x > n || y > tn) return 0;
if(f[x][y]) return f[x][y];
if(r[x][y] != nw[x].r - nw[x].l + 1) return f[x][y] = r[x][y];
else return f[x][y] = r[x][y] + work(x + 1, y + r[x][y]);
}
int main()
{
freopen("lcs.in","r",stdin);
freopen("lcs.out","w",stdout);
scanf("%s\n%s\n", T + 1, S + 1);
tn = strlen(T + 1);
sn = strlen(S + 1);
scanf("%d", &k);
for(int i = 1; i <= k; i++)
{
scanf("%d%d", &a[i].l, &a[i].r);
a[i].l++, a[i].r++;
}
sort(a + 1, a + k + 1, cmp);
nn = 1;
nl[nn] = a[1].l;
nr[nn] = a[1].r;
for(int i = 2; i <= k; i++)
if(a[i].l <= nr[nn])
nr[nn] = max(nr[nn], a[i].r);
else
nl[++nn] = a[i].l, nr[nn] = a[i].r;
if(nl[1] > 1)
for(int i = 1; i < nl[1]; i++)
nw[++n] = (node){i,i};
nl[nn + 1] = sn + 1;
for(int i = 1; i <= nn; i++)
{
nw[++n] = (node){nl[i], nr[i]};
for(int j = nr[i] + 1; j <= nl[i + 1] - 1; j++)
nw[++n] = (node){j, j};
}
for(int i = 1; i <= n; i++)
for(int j = nw[i].l; j <= nw[i].r; j++)
num[i][S[j] - 'a']++;
for(int i = 1; i <= n; i++)
for(int j = 1; j <= tn; j++)
{
int now = 0;
while(j + now <= tn && num[i][T[j + now] - 'a'])
{
num[i][T[j + now] - 'a']--;
now++;
}
r[i][j] = now;
for(int k = 0; k < now; k++)
num[i][T[j + k] - 'a']++;
now = 0;
while(j - now >= 1 && num[i][T[j - now] - 'a'])
{
num[i][T[j - now] - 'a']--;
now++;
}
l[i][j] = now;
for(int k = 0; k < now; k++)
num[i][T[j - k] - 'a']++;
}
for(int i = 1; i <= n + 1; i++)
for(int j = 1; j <= tn + 1; j++)
ans = max(ans, l[i - 1][j - 1] + work(i, j));
printf("%d\n", ans);
return 0;
}