Array Insert

Gary likes to solve problems of the array, but he doesn't like problems that involve queries. His school teacher gave him an assignment full of problems but one of them involve queries. Can you help Gary in solving that problem so that he can go and play with his friends? The problem is :

Given an Array A consisting of N positive integers, you have to answer Q queries on it. Queries can be of the two types: * 1 X Y - Update X at location Y in the array. * 2 L R - Print the sum of range [L, R], i.e. Both L and R are inclusive.

Example:

Input:  n = 5, q = 5, a= {2, 3, 4, 8, 9},  queris={{1, {0, 3}}, {2, {0, 1}}, {2, {0, 4}}, {1, {2, 5}}, {2, {0, 3}}}

Output:

6 27 19

Approach:

C++

#include <bits/stdc++.h>
using namespace std;
long long arr[1000001];
long long tree[2000010];
void build(long long node,
           long long startlong long end)
{
    if (start == end)
    {
        tree[node] = arr[start];
    }
    else
    {
        long long mid = (start + end) / 2;
        build(2 * nodestartmid);
        build(2 * node + 1mid + 1end);
        tree[node] = tree[2 * node] + tree[2 * node + 1];
    }
}
long long query(long long nodelong long start,
                long long endlong long llong long r)
{
    if (r < start || l > end)
        return 0;
    if (start >= l && end <= r)
        return tree[node];
    else
    {
        long long mid = (start + end) / 2;
        long long p1 = query(2 * nodestartmidlr);
        long long p2 = query(2 * node + 1mid + 1endlr);
        return p1 + p2;
    }
}
void update(long long nodelong long start,
            long long endlong long indexlong long val)
{
    if (start == end)
    {
        arr[start] == val;
        tree[node] = val;
    }
    else
    {
        long long mid = (start + end) / 2;
        if (start <= index && index <= mid)
            update(2 * nodestartmidindexval);
        else
            update(2 * node + 1mid + 1endindexval);
        tree[node] = tree[2 * node] + tree[2 * node + 1];
    }
}
int main()
{
    long long n = 5q = 5;

    long long a[n] = {23489};
    for (long long i = 1i <= ni++)
        arr[i] = a[i - 1];
    build(11n);
    vector<pair<intpair<intint>>> queries = {{1, {03}},
                                                 {2, {01}},
                                                 {2, {04}},
                                                 {1, {25}},
                                                 {2, {03}}};
    for (int i = 0i < qi++)
    {
        long long x = queries[i].first;
        long long l = queries[i].second.first;
        long long r = queries[i].second.second;

        if (x == 1)
        {
            update(11nl + 1r);
        }
        else
        {
            long long ans = query(11nl + 1r + 1);
            cout << ans << "\n";
        }
    }
    return 0;
}


No comments:

Post a Comment