Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- using namespace std;
- typedef long long ll;
- typedef pair<int, int> pi;
- typedef vector<int> vi;
- const int MAXN = 300005;
- int n;
- int arr[MAXN];
- int st[4*MAXN];
- void build(int v, int tl, int tr) {
- if (tl == tr) {
- st[v] = arr[tl];
- } else {
- int tm = (tl + tr) / 2;
- build(2*v, tl, tm);
- build(2*v+1, tm+1, tr);
- st[v] = st[2*v] + st[2*v+1];
- }
- }
- int sum(int v, int tl, int tr, int l, int r) {
- if (l > r || l > tr || r < tl) return 0;
- if (l <= tl && tr <= r) return st[v];
- int tm = (tl + tr) / 2;
- return sum(2*v, tl, tm, l, r) + sum(2*v+1, tm+1, tr, l, r);
- }
- void update(int v, int tl, int tr, int pos, int val) {
- if (tl == tr) {
- st[v] = val;
- } else {
- int tm = (tl + tr) / 2;
- if (pos <= tm) {
- update(2*v, tl, tm, pos, val);
- } else {
- update(2*v+1, tm+1, tr, pos, val);
- }
- st[v] = st[2*v] + st[2*v+1];
- }
- }
- void Main() {
- cout << "Enter N, the size of the array, and then N numbers\n";
- cin >> n;
- for (int i = 0; i < n; ++i) {
- cin >> arr[i];
- }
- build(1, 0, n-1);
- cout << "First type of query:\n";
- cout << "1 l r\n";
- cout << "--> Get the sum from l to r (0-indexed)\n";
- cout << "Second type of query:\n";
- cout << "2 x v\n";
- cout << "--> Update element at position x to new value v\n";
- while (true) {
- int t;
- cin >> t;
- if (t == 1) {
- int l, r;
- cin >> l >> r;
- cout << "Sum(" << l << ", " << r << ") = " << sum(1, 0, n-1, l, r) << "\n";
- } else if (t == 2) {
- int x, v;
- cin >> x >> v;
- update(1, 0, n-1, x, v);
- } else {
- cout << "Could not understand query\n";
- }
- }
- }
- int main() {
- // ios::sync_with_stdio(false);
- // cin.tie(0);
- #ifdef _DEBUG
- // freopen("in.txt", "r", stdin);
- // freopen("out.txt", "w", stdout);
- #endif
- #ifndef _DEBUG
- #endif
- Main();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement