树状数组经典题

一个简单的整数问题

题目

第一类指令形如 “C-l-r-d”,表示把数列中第 $l-r$ 个数都加 $d$。

第二类指令形如 “Q-X”,表示询问数列中第 $x$ 个数的值。

对于每个询问,输出一个整数表示答案。

数据范围:$(n, m \in [1, 100000])$

Solution

用树状数组解决动态差分问题。

Code

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
#include <bits/stdc++.h>
using namespace std;
const int N = 5e5 + 5;
typedef long long ll;
int n, m;
ll c[N], a[N];

int lowbit(int x) {
return x & (-x);
}

void add(int x, int y) {
while (x <= n) {
c[x] += y;
x += lowbit(x);
}
}

ll query(int x) {
ll sum = 0;
while (x >= 1) {
sum += c[x];
x -= lowbit(x);
}
return sum;
}

int main()
{
cin >> n >> m;
for (int i = 1; i <= n; i++) cin >> a[i];
while (m--) {
string s;
int x, y, z;
cin >> s;
if (s == "Q") {
cin >> x;
cout << query(x) + a[x] << endl;
} else {
cin >> x >> y >> z;
add(x, z);
add(y + 1, -z);
}
}
return 0;
}

谜一样的牛

题目

给定序列长度 $n$ 和 数组 $a$,$a[i]$ 表示第 $i$ 个数前面有多少个数比它小,复原原序列,原序列为 $1-n$ 的排列。$(n \in [1, 100000])$

Solution

最后一个数的大小明显是一开始就可以推断出来的,假设其大小是 $x$,接着从 $1-n$ 这 $n$ 个数字中把 $x$ 删掉,然后再看倒数第二个数,假设其前面有 $y$ 个数比它小,说明这个数是剩下的数里面第 $y + 1$ 大的数。

由此可以发现,我们可以倒推过来,第 $i$ 个数的大小便是当前还没有被选的数中第 $a[i] + 1$ 小的数。

可以使用树状数组解决,将每个位置置为 $1$ 表示未被选,$0$ 表示已被选,得到的前缀和是单调递增的,因此每次只需要二分查找满足前缀和刚好等于 $a[i] + 1$ 的位置即为当前数的大小。

Code

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
#include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 5;

int n, c[N], a[N], res[N];

int lowbit(int x) {
return x & (-x);
}

void add(int x, int y) {
while (x <= n) {
c[x] += y;
x += lowbit(x);
}
}

int query(int x) {
int sum = 0;
while (x >= 1) {
sum += c[x];
x -= lowbit(x);
}
return sum;
}

int main()
{
cin >> n;
add(1, 1);
for (int i = 2; i <= n; i++) {
cin >> a[i];
add(i, 1);
}
for (int i = n; i >= 1; i--) {
int l = 0, r = n + 1, mid;
while (l + 1 < r) {
mid = l + r >> 1;
if (query(mid) < a[i] + 1) l = mid;
else r = mid;
}
res[i] = r;
add(r, -1);
}
for (int i = 1; i <= n; i++) cout << res[i] << endl;
return 0;
}
作者

Benboby

发布于

2020-10-30

更新于

2021-01-28

许可协议

Your browser is out-of-date!

Update your browser to view this website correctly.&npsb;Update my browser now

×