Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- using namespace std;
- const int maxn = 200005;
- typedef long long ll;
- ll a[maxn];
- int n;
- ll segment_tree[3 * maxn];
- void build_tree(int L, int R, int position) {
- if(L == R) {
- segment_tree[position] = a[L];
- }
- else {
- int mid = (L + R) / 2;
- build_tree(L, mid, 2 * position);
- build_tree(mid + 1, R, 2 * position + 1);
- segment_tree[position] = segment_tree[2 * position] + segment_tree[2 * position + 1];
- }
- }
- // L R i L R j L R
- ll query(int L, int R, int position, int i, int j) {
- if(R < i or j < L) {
- return 0;
- }
- if(i <= L and R <= j) {
- return segment_tree[position];
- }
- int mid = (L + R) / 2;
- return query(L, mid, 2 * position, i, j) + query(mid + 1, R, 2 * position + 1, i, j);
- }
- int main()
- {
- int q;
- cin >> n >> q;
- for(int i = 0; i < n; i++) {
- cin >> a[i];
- }
- build_tree(0, n - 1, 1);
- for(int i = 0; i < q; i++) {
- int a, b;
- cin >> a >> b;
- a--; b--;
- cout << query(0, n - 1, 1, a, b) << endl;
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment