Cod sursa(job #2504703)

Utilizator SochuDarabaneanu Liviu Eugen Sochu Data 5 decembrie 2019 13:24:54
Problema Arbori indexati binar Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.22 kb
#include <bits/stdc++.h>
#define zero(x) (x ^ (x - 1) & x)
#define NMAX 100005

using namespace std;

ifstream f ("aib.in");
ofstream g ("aib.out");

int n , m , x , y;
short type;
int a[NMAX];

void Add(int poz , int value)
{
    for(int i = poz ; i <= n ; i += zero(i))
        a[i] += value;
}

int Sum(int poz)
{
    int ans = 0;

    for(int i = poz ; i >= 1 ; i -= zero(i))
        ans += a[i];

    return ans;
}

int Binarry_Search(int value)
{
    int st = 1 , dr = n , mij = 0 , ans = 0;

    while(st <= dr)
    {
        mij = (dr - st) / 2 + st;

        if(Sum(mij) >= value)
        {
            ans = mij;
            dr = mij - 1;
        }
        else st = mij + 1;
    }

    if(Sum(ans) == value)
        return ans;
    return -1;
}

int main()
{
    int i;

    f >> n >> m;

    for(i = 1 ; i <= n ; i++)
    {
        f >> x;
        Add(i , x);
    }

    for(i = 1 ; i <= m ; i++)
    {
        f >> type >> x;

        if(type != 2)
            f >> y;

        if(type == 0)
            Add(x , y);
        else if(type == 1)
            g << Sum(y) - Sum(x - 1) << '\n';
        else g << Binarry_Search(x) << '\n';
    }

    return 0;
}