Cod sursa(job #1410408)

Utilizator Al3ks1002Alex Cociorva Al3ks1002 Data 31 martie 2015 01:18:09
Problema Arbori indexati binar Scor 50
Compilator cpp Status done
Runda Arhiva educationala Marime 1.74 kb
#include<cstdio>
#include<fstream>
#include<iostream>
#include<iomanip>
#include<algorithm>
#include<vector>
#include<bitset>
#include<deque>
#include<queue>
#include<set>
#include<map>
#include<cmath>
#include<cstring>
#include<ctime>
#include<cstdlib>
#include<unordered_map>

#define ll long long
#define pb push_back
#define mp make_pair
#define pii pair<int,int>
#define pll pair<ll,ll>
#define all(x) (x).begin(), (x).end()
#define fi first
#define se second

using namespace std;

const int nmax = 100005;

int n, m, i, x, y, poz, val, op, lim, aib[nmax];

void update(int poz, int val)
{
    for(int i = poz; i <= n; i += i & (-i))
        aib[i] += val;
}

int sum(int poz)
{
    int r = 0;
    for(int i = poz; i; i -= i & (-i))
        r += aib[i];
    return r;
}

int jmen(int x)
{
    int r = 0;
    for(int step = lim; step; step /= 2)
        if(r + step <= n && aib[r + step] <= x)
        {
            x -= aib[r + step];
            r += step;
        }

    if(x)
        return -1;
    return r;
}

int main()
{
    freopen("aib.in", "r", stdin);
    freopen("aib.out", "w", stdout);

    scanf("%d%d", &n, &m);

    for(i = 1; i <= n; i++)
    {
        scanf("%d", &x);
        update(i, x);
    }

    for(lim = 1; (lim * 2) <= n; lim *= 2);

    for(; m; m--)
    {
        scanf("%d", &op);

        if(op == 0)
        {
            scanf("%d%d", &poz, &val);
            update(poz, val);
        }
        else if(op == 1)
        {
            scanf("%d%d", &x, &y);
            printf("%d\n", sum(y) - sum(x - 1));
        }
        else
        {
            scanf("%d", &x);
            printf("%d\n", jmen(x));
        }
    }

    return 0;
}