Cod sursa(job #216100)

Utilizator alex_mircescuAlex Mircescu alex_mircescu Data 22 octombrie 2008 20:19:57
Problema Arbori indexati binar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.18 kb
#include <stdio.h>
#define max 100001

long a[max], i, n, s, x, y, q, tq, pow, j;

long LSB(long x) {
    return (x & (x - 1)) ^ x;
} 

void insert(long i, long x) {
	for(; i <= n; i += LSB(i)) {
		a[i] += x;
	}
}

long sum(long x) {
    long ret = 0;
    for (; x ; x -= LSB(x)) {
		ret += a[x];
	}
    return ret;
}

int main() {
    freopen("aib.in", "r", stdin);
    freopen("aib.out", "w", stdout);
    scanf("%ld%ld", &n, &q);
    for (i = 1; i <= n; ++i) {
       scanf("%ld", &x);
       insert(i, x);
    }
    for (pow = 1; pow <= n ; pow <<= 1);
    pow >>= 1;
    while (q--) {
        scanf("%ld", &tq);
        if (tq == 0) {
           scanf("%ld %ld", &x, &y);
           insert(x, y);
           continue;
        }
        if (tq == 1) {
			scanf("%ld %ld", &x, &y);
			printf("%ld\n", sum(y) - sum(x - 1));
			continue;
        }
        scanf("%ld", &x);
        i = 0, j = pow, s = 0;
        while (j) {
			if (i + j <= n && a[i + j] + s <= x ) {
				i += j;
				s += a[i];
			}
            j >>= 1;
        }
        if (i == 0) {
			printf("-1\n");
		} else {   
			if (s == x) {
				printf("%ld\n",i);
			} else {
				printf("-1\n");
			}
		}
    }
    
    return 0;
}