本体标签是线段树,这里的做法是用线段树维护哈希。思路是对每一个线段树的节点添加一个hash的属性,具体的如下式所述:
其中 , 分别代表线段树上节点 所管辖的区间的做右端点。
那么用等比数列的求和公式,易知,题目所需区间的哈希值为:
其中 为首项, 为区间长度, 函数为乘法逆元函数。
基于上述两式,我们只需判断 是否等于 即可。
哈希出现哈希碰撞的概率几乎为零。
于是便可写出代码:
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
const int N = 500005;
const ll M = 1999999973LL;
const ll P = 97;// 任意质数即可,最好不是2
inline ll qpow(ll a, ll m)
{
ll res = 1;
while (m)
{
if (m & 1)
res = res * a % M;
m >>= 1;
a = a * a % M;
}
return res;
}
struct node
{
int l, r;
ll h;
ll mx, mn;
} t[N << 2];
int n, Q, a[N], cnt;
inline void pushup(const int &u)
{
int L = u << 1, R = u << 1 | 1;
t[u].h = (t[L].h + t[R].h) % M;
t[u].mx = max(t[L].mx, t[R].mx);
t[u].mn = min(t[L].mn, t[R].mn);
}
void build(int u, const int &l, const int &r)
{
t[u].l = l, t[u].r = r;
if (l == r)
{
t[u].h = qpow(P, a[l]) % M;
t[u].mx = a[l];
t[u].mn = a[l];
return;
}
int mid = (t[u].l + t[u].r) >> 1;
build(u << 1, l, mid);
build(u << 1 | 1, mid + 1, r);
pushup(u);
}
void update(int u, const int &pos, const int &v)
{
if (t[u].l == pos && t[u].r == pos)
{
a[pos] = v;
t[u].h = qpow(P, v) % M;
t[u].mx = v;
t[u].mn = v;
return;
}
int mid = (t[u].l + t[u].r) >> 1;
if (pos <= mid)
update(u << 1, pos, v);
else
update(u << 1 | 1, pos, v);
pushup(u);
}
inline ll query_h(int u, const int &l, const int &r)
{
if (l <= t[u].l && t[u].r <= r)
return t[u].h;
int mid = (t[u].l + t[u].r) >> 1;
ll h = 0;
if (l <= mid)
h = (h + query_h(u << 1, l, r)) % M;
if (mid < r)
h = (h + query_h(u << 1 | 1, l, r)) % M;
return h;
}
inline ll query_mx(int u, const int &l, const int &r)
{
if (l <= t[u].l && t[u].r <= r)
return t[u].mx;
int mid = (t[u].l + t[u].r) >> 1;
ll res = LLONG_MIN;
if (l <= mid)
res = max(res, query_mx(u << 1, l, r));
if (mid < r)
res = max(res, query_mx(u << 1 | 1, l, r));
return res;
}
inline ll query_mn(int u, const int &l, const int &r)
{
if (l <= t[u].l && t[u].r <= r)
return t[u].mn;
int mid = (t[u].l + t[u].r) >> 1;
ll res = LLONG_MAX;
if (l <= mid)
res = min(res, query_mn(u << 1, l, r));
if (mid < r)
res = min(res, query_mn(u << 1 | 1, l, r));
return res;
}
ll inv(ll x) { return qpow(x, M - 2); }
inline bool check(int l, int r, int k)
{
int len = r - l + 1;
if (len == 1)
return true;
ll st = query_mn(1, l, r);
ll ed = query_mx(1, l, r);
if (ed - st != (ll)k * (len - 1))
return false;
if (k == 0)
{
ll need = qpow(P, st) * len % M;
ll hash = query_h(1, l, r);
return hash == need;
}
ll need = qpow(P, st) * (qpow(P, len * k) - 1 + M) % M * inv((qpow(P, k) - 1 + M) % M) % M;
ll hash = query_h(1, l, r);
return hash == need;
}
int main()
{
scanf("%d %d", &n, &Q);
for (int i = 1; i <= n; i++)
scanf("%d", &a[i]);
build(1, 1, n);
while (Q--)
{
int opt;
scanf("%d", &opt);
if (opt == 1)
{
int x, y;
scanf("%d %d", &x, &y);
x ^= cnt, y ^= cnt;
update(1, x, y);
}
else
{
int l, r, k;
scanf("%d %d %d", &l, &r, &k);
l ^= cnt, r ^= cnt, k ^= cnt;
if (l > r)
swap(l, r);
if (check(l, r, k))
puts("Yes"), cnt++;
else
puts("No");
}
}
return 0;
}