题意
- 给你一个长度为 n n n 的序列 a a a, q q q 次询问,每次询问一段区间 [ l , r ] [l,r] [l,r] 内有多少种数值域在 [ x , y ] [x,y] [x,y] 内(值相等的数算同一种)( a i ≤ n ≤ 1 0 5 , q ≤ 1 0 6 a_i\le n\le10^5,q\le 10^6 ai≤n≤105,q≤106)。
没有修改自然考虑莫队,按一般的方法我们要会插入删除 n q n \sqrt q nq 次,询问 q q q 次,如果用树状数组维护的话复杂度是 O ( n q log n ) O(n\sqrt q\log n) O(nqlogn)的。
我们发现询问次数与插入删除次数及其不对称,考虑用均值法优化,增大询问复杂度来减小修改复杂度,那么只需要值域分块即可,复杂度 O ( n q ) O(n \sqrt q) O(nq) 。
#include <bits/stdc++.h>
#define For(i, a, b) for (int i = a; i <= b; ++ i)
using namespace std;
inline int read()
{
int _ = 0, __ = getchar(), ___ = 1;
for (; !isdigit(__); __ = getchar()) if (__ == '-') ___ = -1;
for (; isdigit(__); __ = getchar()) _ = (_ << 3) + (_ << 1) + (__ ^ 48);
return _ * ___;
}
const int N = 1e5 + 5;
int a[N], be[N], rel[N];
int st[N], ed[N], cnt;
struct Que { int id, l, r, x, y; } Q[N * 10];
bool cmp(Que A, Que B) { return rel[A.l] == rel[B.l] ? A.r < B.r : A.l < B.l; }
int cnt1[N], cnt2[N];
void Insert(int pos) { if (++ cnt1[a[pos]] == 1) ++ cnt2[be[a[pos]]]; }
void Delete(int pos) { if (-- cnt1[a[pos]] == 0) -- cnt2[be[a[pos]]]; }
int Query(int l, int r)
{
int res = 0;
if (be[l] + 1 <= be[r] - 1)
{
For(i, be[l] + 1, be[r] - 1) res += cnt2[i];
For(i, l, ed[be[l]]) res += cnt1[i] != 0;
For(i, st[be[r]], r) res += cnt1[i] != 0;
}
else For(i, l, r) res += cnt1[i] != 0;
return res;
}
int main()
{
static int ans[N * 10], n = read(), q = read(), sz1, sz2;
sz1 = sqrt(n), sz2 = sqrt((double)n * n / q);
For(i, 1, n)
{
if (i % sz1 == 1) st[++ cnt] = i;
if (i % sz1 == 0 || i == n) ed[cnt] = i;
a[i] = read(), be[i] = cnt, rel[i] = i / sz2;
}
For(i, 1, q)
{
Q[i].id = i;
Q[i].l = read(), Q[i].r = read();
Q[i].x = read(), Q[i].y = read();
}
sort(Q + 1, Q + q + 1, cmp);
int l = 1, r = 0;
For(i, 1, q)
{
while (r < Q[i].r) Insert(++ r);
while (r > Q[i].r) Delete(r --);
while (l > Q[i].l) Insert(-- l);
while (l < Q[i].l) Delete(l ++);
ans[Q[i].id] = Query(Q[i].x, Q[i].y);
}
For(i, 1, q) printf("%d\n", ans[i]);
return 0;
}