Cod sursa(job #2220180)

Utilizator Johnny07Savu Ioan-Daniel Johnny07 Data 10 iulie 2018 20:14:22
Problema Arbori indexati binar Scor 50
Compilator cpp Status done
Runda Arhiva educationala Marime 1.27 kb
#include <iostream>
#include <fstream>
using namespace std;
ifstream f("aib.in");
ofstream g("aib.out");

int n,m,aib[100010];

void update(int poz, int val)
{

    while (poz<=n)
    {
        aib[poz]+=val;
        poz+=poz&(-poz);
    }

}

void sum (int start, int stop)
{
    start--;
    long long sum1=0, sum2=0;
    while (start>0)
    {
        sum1+=aib[start];
        start-=start&(-start);
    }
    while (stop>0)
    {
        sum2+=aib[stop];
        stop-=stop&(-stop);
    }
    g<<sum2-sum1<<"\n";
}


void gasesc (int val)
{

    int poz=1;
    int i=0;
    while (poz<=n) poz*=2;
     i=0;
     while (poz!=0)
     {
         if (i+poz<=n)
         {
             if (val>=aib[i+poz])
             {
                 val-=aib[i+poz];
                 i+=poz;
             }

             if (val==0) {g<<i<<"\n";return;}
             }
             poz/=2;
     }
     g<<"-1\n";

}


int main()
{
    int i,c,x,y;
f>>n>>m;
for (i=1;i<=n;i++)
{
    f>>x;
    update(i, x);
}
for (i=1;i<=m;i++)
{
    f>>c;
    if (c==0) {f>>x>>y;  update(x, y); }
    if (c==1)
    {
        f>>x>>y;
        sum(x, y);
    }
    if (c==2)
    {
        f>>x;
        gasesc(x);
    }
}


    return 0;
}