Cod sursa(job #1139419)

Utilizator beldeabogdanBogdan Beldea beldeabogdan Data 11 martie 2014 09:37:31
Problema Arbori indexati binar Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.42 kb
#include <cstdio>
#include <algorithm>
#define nmax 100005
using namespace std;

long long aib[nmax];
int n,m;

void update(unsigned int pos,int val) {
    while (pos <= n) {
        int lsb = pos&(-pos);
        aib[pos] += val;
        pos += lsb;
    }
}

long long query(int pos) {
    long long s = 0;
    while (pos > 0) {
        int lsb = pos&(-pos);
        s += aib[pos];
        pos -= lsb;
    }
    return s;
}

void Q0() {
    int a,b;
    scanf("%d %d",&a,&b);
    update(a,b);
}

void Q1() {
    int a,b;
    scanf("%d %d",&a,&b);
    if (a > b) swap(a,b);
    long long sum;
    if (a>1) sum = query(b) - query(a-1);
    else sum = query(b);
    printf("%lld\n",sum);
}

void Q2() {
    int a;
    int start=1;
    scanf("%d",&a);
    while (1 << start <= n && query(1 << start) <= a) start += 1;
    start -= 1;
    int conf = 1<<start;
    for (int i=start-1;i>=1;i--) {
        if (conf+(1<<i) <= n && query(conf+(1<<i)) <= a) conf += 1<<i;
    }
    printf("%d\n",conf);
}

int main() {
    freopen("aib.in","r",stdin);
    freopen("aib.out","w",stdout);
    scanf("%d %d\n",&n,&m);
    for (int i=1;i<=n;i++)  {
        int aux;
        scanf("%d",&aux);
        update(i,aux);
    }
    for (int i=1;i<=m;i++) {
        int type;
        scanf("%d",&type);
        if (type == 0) Q0();
        else if (type == 1) Q1();
        else Q2();
    }
    return 0;
}