单哈希模数过不去捏,求求能过的哈希模数。
#include <algorithm>
#include <iostream>
#include <cstring>
#include <cstdio>
#include <map>
#define int long long
using namespace std;
using PII = pair<int, int>;
const int N = 200010;
const int P = 23, mod = 19260817;
int n, m, a[N], b[N], ans;
int h1[N], h2[N], p[N], Base;
map<int, bool> Map;
PII tmp[N];
struct node {
int l, r;
int hash, size;
}tr[N << 2];
#define ls u << 1
#define rs u << 1 | 1
int Mod(int x) {
return (x % mod + mod) % mod;
}
void pushup(int u) {
tr[u].size = tr[ls].size + tr[rs].size;
tr[u].hash = Mod(tr[rs].hash + Mod(tr[ls].hash * p[tr[rs].size]));
}
void build(int u, int l, int r) {
tr[u] = {l, r, 0, 0};
if (l == r) return;
int mid = l + r >> 1;
build(ls, l, mid), build(rs, mid + 1, r);
}
void insert(int u, int x, int v) {
if (tr[u].l == tr[u].r) {
tr[u].hash = v; tr[u].size = 1;
return;
}
int mid = tr[u].l + tr[u].r >> 1;
if (x <= mid) insert(ls, x, v);
else insert(rs, x, v);
pushup(u);
}
void remove(int u, int x) {
if (tr[u].l == tr[u].r) {
tr[u].hash = tr[u].size = 0;
return;
}
int mid = tr[u].l + tr[u].r >> 1;
if (x <= mid) remove(ls, x);
else remove(rs, x);
pushup(u);
}
int get_hash(int l, int r) {
return ((h2[r] - h2[l - 1] * p[r - l + 1] % mod) % mod + mod) % mod;
}
signed main() {
scanf("%lld%lld", &n, &m);
for (int i = 1; i <= n; i ++ )
scanf("%lld", &a[i]);
for (int i = 1; i <= m; i ++ )
scanf("%lld", &b[i]);
p[0] = 1;
for (int i = 1; i <= n; i ++ )
h1[i] = (h1[i - 1] * P % mod + a[i]) % mod;
for (int i = 1; i <= m; i ++ )
h2[i] = (h2[i - 1] * P % mod + b[i]) % mod;
for (int i = 1; i <= m; i ++ )
p[i] = p[i - 1] * P % mod;
for (int i = 0; i < n; i ++ )
Base = (Base + p[i]) % mod;
for (int i = 0; i <= m - n; i ++ ) // O(m \log n) has been used. Here.
Map[(h1[n] + Base * i % mod) % mod] = true;
for (int i = 1; i <= m; i ++ )
tmp[i] = {b[i], i};
sort(tmp + 1, tmp + m + 1);
build(1, 1, m);
for (int i = 1; i <= n; i ++ )
insert(1, tmp[i].second, tmp[i].first);
for (int i = n + 1; i <= m; i ++ ) {
int hash = tr[1].hash;
if (Map[hash]) ans ++ ;
remove(1, tmp[i - n].second);
insert(1, tmp[i].second, tmp[i].first);
}
if (Map[tr[1].hash]) ans ++ ;
cout << ans << endl;
return 0;
}
p=13,mod=109+7
p=1331,mod=998244353
p=13,mod=999988883
都不过。