Given an array of n integers, your task is to process q queries of the following types:
- update the value at position k to u
- what is the sum of values in the range [a,b]?
Example:
Input: n = 8, q = 4, a = {3, 2, 4, 5, 1, 1, 5, 3}, queries = {{2, 1, 4}, {2, 5, 6}, {1, 3, 1}, {2, 1, 4}}
Output:
14 2 11
Approach:
C++
#include <bits/stdc++.h>using namespace std;long long arr[1000001];long long tree[4010001];void build(long long node, long long start, long long end){if (start == end){tree[node] = arr[start];return;}long long mid = (start + end) / 2;build(2 * node, start, mid);build(2 * node + 1, mid + 1, end);tree[node] = tree[2 * node] + tree[2 * node + 1];}long long query(long long node, long long start,long long end, long long l, long long r){if (r < start || l > end)return 0;if (l <= start && r >= end)return tree[node];long long mid = (start + end) / 2;long long p1 = query(2 * node, start, mid, l, r);long long p2 = query(2 * node + 1, mid + 1, end, l, r);return p1 + p2;}void update(long long node, long long start,long long end, long long index, long long val){if (start == end){tree[node] = val;return;}int mid = (start + end) / 2;if (index <= mid)update(2 * node, start, mid, index, val);else{update(2 * node + 1, mid + 1, end, index, val);}tree[node] = tree[2 * node] + tree[2 * node + 1];}int main(){long long n = 8, q = 4;vector<int> a = {3, 2, 4, 5, 1, 1, 5, 3};vector<vector<long long>> queries = {{2, 1, 4},{2, 5, 6},{1, 3, 1},{2, 1, 4}};for (long long i = 1; i <= n; i++)arr[i] = a[i - 1];build(1, 1, n);for (long long i = 0; i < q; i++){long long x = queries[i][0];long long l = queries[i][1];long long r = queries[i][2];if (x == 1){arr[l] = r;update(1, 1, n, l, r);}elsecout << query(1, 1, n, l, r) << "\n";}return 0;}
No comments:
Post a Comment