Cod sursa(job #1161200)

Utilizator alexandru70Ungurianu Alexandru alexandru70 Data 31 martie 2014 08:45:04
Problema Arbori indexati binar Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.83 kb
#include <iostream>
#include <fstream>
 
using namespace std;
 
ifstream in ("aib.in");
ofstream out ("aib.out");

typedef unsigned long long Big;
 
Big bit[100001],n;
 
Big RightmostOne(Big x) {
    return x&(-x);
}
/*
void BIT_Gen() {
    for(int i = 1; i <= n; ++i) {
        for(int j = i - RightmostOne(i) + 1; j <= i; j++) {
            //cerr << i;
            bit[i]+=v[j];
        }
    }
}
*/
void BIT_Add(Big idx, Big val) {
    for(Big i = idx; i <= n; i+=RightmostOne(i)) {
        //cerr << i;
        bit[i]+=val;
    }
}
 
Big BIT_Compute(int idx) {
    Big res = 0;
    for(Big i = idx; i > 0; i-=RightmostOne(i)) {
        res+=bit[i];
    }
    return res;
}
 
Big BIT_Find(Big val) {
    Big step = 1;
    for(;step<n;step<<=1);
    step>>=1;
    Big i;
    for(i = step; step!=0;step>>=1) {
        if(i>=n){
            i-=step;
            continue;
        }
        Big currV = BIT_Compute(i+1);
        if(currV == val)return i+1;
        if(currV > val)i-=step;
        if(currV < val)i+=step;
    }
    if(BIT_Compute(i+1)==val)return i+1;
    return -1;
}
 
int main() {
    int m;
    in >> n >> m;
     
    for (int i = 1; i <= n; ++i) {
        int t;
        in >> t;
        BIT_Add(i,t);
    }
    for(int i = 0; i < m; ++i) {
        int c;
        in >> c;
        switch(c) {
            case 0:
                Big i,val;
                in >> i >> val;
                BIT_Add(i,val);
                break;
            case 1:
                Big st,fn;
                in >> st >> fn;
                out << BIT_Compute(fn)-BIT_Compute(st-1) << '\n';
                break;
            case 2:
                Big k;
                in >> k;
                out << BIT_Find(k)<<'\n';
                break;
        }
    }
    return 0;
}