给定一个匹配串和一个模式串,求模式串有多少个连续子串能够修改不超过 (3) 个字符变成匹配串
(lenleq10^5)
hash
枚举子串左端点,hash 求 lcp 枚举断点,接着跳过断点,记作一次修改,最多修改 (3) 次。特判修改 (3) 次后剩余部分是否相等。
时间复杂度 (O(nlog n))
代码
#include <bits/stdc++.h>
using namespace std;
typedef unsigned long long ull;
const int maxn = 1e5 + 10;
int Tests;
int n, m;
char str[maxn], s[maxn];
ull pw[maxn], sum1[maxn], sum2[maxn];
ull getsum(ull* a, int l, int r) {
return a[r] - a[l - 1] * pw[r - l + 1];
}
int query(int x, int y) {
int l = 0, r = m - y + 1, mid;
while (l < r) {
mid = (l + r + 1) >> 1;
getsum(sum1, x, x + mid - 1) == getsum(sum2, y, y + mid - 1) ? l = mid : r = mid - 1;
}
return r;
}
int check(int x) {
int y = 1;
for (int i = 0; i < 3; i++) {
int tmp = query(x, y);
x += tmp + 1, y += tmp + 1;
if (y > m) return 1;
}
return getsum(sum1, x, x + m - y) == getsum(sum2, y, m);
}
void solve() {
scanf("%s %s", str + 1, s + 1);
n = strlen(str + 1), m = strlen(s + 1);
for (int i = 1; i <= n; i++) {
sum1[i] = sum1[i - 1] * 131 + str[i];
}
for (int i = 1; i <= m; i++) {
sum2[i] = sum2[i - 1] * 131 + s[i];
}
int ans = 0;
for (int i = 1; i <= n - m + 1; i++) {
ans += check(i);
}
printf("%d
", ans);
}
int main() {
pw[0] = 1;
for (int i = 1; i < 100001; i++) {
pw[i] = pw[i - 1] * 131;
}
scanf("%d", &Tests);
while (Tests--) {
solve();
}
return 0;
}