Cod sursa(job #963664)

Utilizator dutzulBodnariuc Dan Alexandru dutzul Data 17 iunie 2013 23:19:15
Problema Arbori indexati binar Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.22 kb
#include <iostream>
#include <fstream>
using namespace std;

#define lsb(X) (X&(X^(X-1)))
#define LE 100666
#define ll long long

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

int n,m;
ll tree[LE],vv;
int i,typ;

void update(int pos,ll value) {

    for(; pos<=n; pos+=lsb(pos))
        tree[pos]+=value;
}
ll query(int pos) {
    ll result=0;

    for(; pos>0; pos-=lsb(pos))
        result+=tree[pos];

    return result;
}
int sch(ll smax) {
    ll step,pos,total=0;

    for(step=1; step<=n; step<<=1);

    for(pos=0; step; step>>=1)
        if (pos+step<=n&&total+tree[pos+step]<=smax) {
            pos+=step;
            total+=tree[pos];
        }

    return ((total==smax&&pos==0)?pos:-1);
}

int main() {

    f>>n>>m;
    for(i=1; i<=n; ++i) {
        f>>vv;
        update(i,vv);
    }

    for(i=1; i<=m; ++i) {
        f>>typ;
        ll aa,bb;

        if (typ==0) {
            f>>aa>>bb;
            update (aa,bb);
        }
        if (typ==1) {
            f>>aa>>bb;
            g<<query(bb)-query(aa-1)<<'\n';
        }
        if (typ==2) {
            f>>aa;
            g<<sch(aa)<<'\n';
        }
    }



    f.close();
    g.close();
    return 0;
}