bzoj4892 [TJOI2017]DNA

\(\verb|bzoj4892 [TJOI2017]DNA|\)

给定一个匹配串和一个模式串,求模式串有多少个连续子串能够修改不超过 \(3\) 个字符变成匹配串

\(len\leq10^5\)

hash


枚举子串左端点,hash 求 lcp 枚举断点,接着跳过断点,记作一次修改,最多修改 \(3\) 次。特判修改 \(3\) 次后剩余部分是否相等。

时间复杂度 \(O(n\log 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\n", 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;
}
上一篇:【洛谷3822】[NOI2017] 整数(线段树压位).md


下一篇:题解 Luogu P3370