【题解】SP3266 KQUERY

题目传送门

前言

现有题解大多写的都是主席树,这里提供一个好想而且好写的分块做法。

前置芝士

分块

分析

我们考虑对原数组进行分块,每个块内分别排序,在处理询问时,我们分两种情况讨论。

  1. 若 \(l\) 和 \(r\) 在同一块中,则暴力扫描统计答案。
  2. 若 \(l\) 和 \(r\) 在不同块中,则对 \(l\) 和 \(r\) 所处的不完整块进行暴力统计,中间的完整块直接二分查找得出答案。

我在程序中取得块长为 \(\sqrt n\),最终复杂度为 \(O(q\log n \sqrt n)\)

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#include <bits/stdc++.h>

using namespace std;
const int N = 3e4 + 10, B = 175;
int a[N], id[N];
vector<int> b[B];

int read()
{
int x = 0, y = 1; char c = getchar();
while (c < '0' || c > '9') {if (c == '-') y = -1; c = getchar();}
while (c >= '0' && c <= '9') x = x * 10 + c - '0', c = getchar();
return x * y;
}

bool cmp(int i, int j)
{
return i > j;
}

int query(int l, int r, int k)
{
if (id[l] == id[r])
{
int res = 0;
for (int i = l; i <= r; i++)
if (a[i] > k) res++;
return res;
}
int res = 0;
for (int i = l; id[i] == id[l]; i++)
if (a[i] > k) res++;
for (int i = r; id[i] == id[r]; i--)
if (a[i] > k) res++;
for (int i = id[l] + 1; i <= id[r] - 1; i++)
res += lower_bound(b[i].begin(), b[i].end(), k, greater<int>()) - b[i].begin();
return res;
}

int main()
{
int n = read();
for (int i = 1; i <= n; i++)
{
a[i] = read();
id[i] = (i - 1) / B + 1;
b[id[i]].push_back(a[i]);
}
for (int i = 1; i <= id[n]; i++)
sort(b[i].begin(), b[i].end(), cmp);
int q = read();
while (q--)
{
int l = read(), r = read(), k = read();
printf("%d\n", query(l, r, k));
}
return 0;
}