Cod sursa(job #2669165)

Utilizator MohneaGosuMihnea Gusu MohneaGosu Data 6 noiembrie 2020 12:05:11
Problema Arbori indexati binar Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.42 kb
#include <fstream>

using namespace std;
ifstream Gigi ("aib.in");
ofstream Marcel ("aib.out");
int n,m,n1,t,a,b;
short int test;
int binary(int x)
{
    x--;
    x |= x >> 1;
    x |= x >> 2;
    x |= x >> 4;
    x |= x >> 8;
    x |= x >> 16;
    x++;
    return x;
}
int lsb(int x)
{
    return (x&(x-1))^x;
}
int aib[131072];
void update (int poz, int val)
{
    while (poz<=n1)
    {
        aib[poz]+=val;
        poz+=lsb(poz);
    }
}
int sum(int x)
{
    int s=0;
    while (x){
        s+=aib[x];
        x-=lsb(x);
    }
    return s;
}
int cauta (int x)
{
    int st=1,dr=n1,mij;
    while (st<=dr){
        mij=(st+dr)/2;
        if (x==sum(mij)){
            if (!mij) return -1;
            return mij;
        }
        else {
            if (x<sum(mij)){
                dr=mij;
            }
            else {
                st=mij+1;
            }
        }
    }
    return -1;
}
int main()
{
    Gigi>>n>>m;
    int i;
    n1=binary(n);
    for (i=1;i<=n;i++){
        Gigi>>t;
        update(i,t);
    }
    for (;m;m--){
        Gigi>>test;
        if (test<2){
            Gigi>>a>>b;
            if (test){
                Marcel<<sum(b)-sum(a-1)<<"\n";
            }
            else {
                update(a,b);
            }
        }
        else {
            Gigi>>a;
            Marcel<<cauta(a)<<"\n";
        }
    }
    return 0;
}