-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathbinary_lifting.cpp
More file actions
66 lines (61 loc) · 1.29 KB
/
binary_lifting.cpp
File metadata and controls
66 lines (61 loc) · 1.29 KB
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
59
60
61
62
63
64
65
66
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_pbds;
template <class T>
using ordered_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
#define int long long int
#define endl '\n'
#define pb push_back
#define pi pair<int, int>
#define pii pair<int, pi>
#define fir first
#define sec second
#define MAXN 500001
#define mod 1000000007
struct item
{
int nxt, sum;
};
int n, q;
int v[MAXN];
item st[MAXN][21];
signed main()
{
cin >> n >> q;
for (int i = 0; i < n; i++)
cin >> v[i];
for (int i = 0; i < n; i++)
{
st[i][0].nxt = min(i + 1, n - 1);
st[i][0].sum = v[st[i][0].nxt];
}
for (int i = 1; i < 21; i++)
{
for (int v = 0; v < n; v++)
{
st[v][i].nxt = st[st[v][i - 1].nxt][i - 1].nxt;
st[v][i].sum = st[v][i - 1].sum + st[st[v][i - 1].nxt][i - 1].sum;
}
}
while (q--)
{
int l, r;
cin >> l >> r;
r--;
int ans = v[l], len = r - l;
for (int i = 20; i >= 0; i--)
{
if (len & (1 << i))
{
ans += st[l][i].sum;
l = st[l][i].nxt;
}
}
cout << ans << endl;
}
return 0;
}
// simple range sum query with binary lifting
// https://judge.yosupo.jp/problem/static_range_sum