今天我刷题了吗
搜索文档…
主席树
1
#include <bits/stdc++.h>
2
3
using namespace std;
4
using ll = long long;
5
using p = pair<int, int>;
6
const double pi(acos(-1));
7
const int inf(0x3f3f3f3f);
8
const int mod(1e9 + 7);
9
const int maxn(2e5 + 10);
10
int cnt, a[maxn], root[maxn];
11
vector<int> nums;
12
13
struct node {
14
int l, r, sum;
15
} tree[maxn * 40];
16
17
template<typename T = int>
18
inline const T read()
19
{
20
T x = 0, f = 1;
21
char ch = getchar();
22
while (ch < '0' || ch > '9') {
23
if (ch == '-') f = -1;
24
ch = getchar();
25
}
26
while (ch >= '0' && ch <= '9') {
27
x = (x << 3) + (x << 1) + ch - '0';
28
ch = getchar();
29
}
30
return x * f;
31
}
32
33
template<typename T>
34
inline void write(T x, bool ln)
35
{
36
if (x < 0) {
37
putchar('-');
38
x = -x;
39
}
40
if (x > 9) write(x / 10, false);
41
putchar(x % 10 + '0');
42
if (ln) putchar(10);
43
}
44
45
inline int getId(int val)
46
{
47
return int(lower_bound(nums.begin(), nums.end(), val) - nums.begin()) + 1;
48
}
49
50
void insert(int l, int r, int pos, int pre, int& cur)
51
{
52
cur = ++cnt;
53
tree[cur] = tree[pre];
54
++tree[cur].sum;
55
if (l == r) return;
56
int mid = (l + r) >> 1;
57
if (pos <= mid) {
58
insert(l, mid, pos, tree[pre].l, tree[cur].l);
59
} else {
60
insert(mid + 1, r, pos, tree[pre].r, tree[cur].r);
61
}
62
}
63
64
int query(int l, int r, int k, int pre, int cur)
65
{
66
if (l == r) return l;
67
int mid = (l + r) >> 1;
68
int dif = tree[tree[cur].l].sum - tree[tree[pre].l].sum;
69
if (k <= dif) {
70
return query(l, mid, k, tree[pre].l, tree[cur].l);
71
}
72
return query(mid + 1, r, k - dif, tree[pre].r, tree[cur].r);
73
}
74
75
int main()
76
{
77
#ifdef ONLINE_JUDGE
78
#else
79
freopen("input.txt", "r", stdin);
80
#endif
81
ios::sync_with_stdio(false);
82
int n = read(), m = read();
83
for (int i = 1; i <= n; ++i) {
84
nums.push_back(a[i] = read());
85
}
86
sort(nums.begin(), nums.end());
87
nums.erase(unique(nums.begin(), nums.end()), nums.end());
88
for (int i = 1; i <= n; ++i) {
89
int pos = getId(a[i]);
90
insert(1, (int)nums.size(), pos, root[i - 1], root[i]);
91
}
92
while (m--) {
93
int l = read(), r = read(), k = read();
94
write(nums[query(1, (int)nums.size(), k, root[l - 1], root[r]) - 1], true);
95
}
96
return 0;
97
}
Copied!
最近更新 1yr ago
复制链接