Cod sursa(job #3363368)

Utilizator horia.boeriuBoeriu Horia Andrei horia.boeriu Data 17 august 2026 01:55:16
Problema Arbori indexati binar Scor 50
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.77 kb
#include <bits/stdc++.h>

using namespace std;
const int MAXN = 100000;
int aib[MAXN + 1];
int n, p2;

void addBit(int poz, int val) {
    while (poz <= n) {
        aib[poz] += val;
        poz += (poz & (-poz));
    }
}
int bitSum(int poz) {
    int s;
    s = 0;
    while (poz > 0) {
        s += aib[poz];
        poz &= (poz - 1);
    }
    return s;
}
int findPoz(int sum) {
    int poz, s, p;
    poz = s = 0;
    for (p = p2; p >= 0; p--) {
        if (poz + (1 << p) <= n && s + aib[poz + (1 << p)] <= sum) {
            poz += (1 << p);
            s += aib[poz];
        }
    }
    if (s == sum) {
        return poz;
    }
    return -1;
}
int readInt(FILE *fin) {
    int x;
    char ch;
    ch = fgetc(fin);
    while (isspace(ch)) {
        ch = fgetc(fin);
    }
    x = 0;
    while (isdigit(ch)) {
        x = x * 10 + ch - '0';
        ch = fgetc(fin);
    }
    return x;
}
int main()
{
    FILE *fin, *fout;
    int m, i, j, a, b, cer;
    fin = fopen("aib.in", "r");
    n = readInt(fin);
    m = readInt(fin);
    p2 = 1;
    while ((1 << p2) <= n) {
        p2++;
    }
    p2--;
    for (i = 1; i <= n; i++) {
        aib[i] += readInt(fin);
        j = i + (i & (-i));
        if (j <= n) {
            aib[j] += aib[i];
        }
    }
    fout = fopen("aib.out", "w");
    for (i = 0; i < m; i++) {
        cer = readInt(fin);
        a = readInt(fin);
        if (cer == 2) {
            fprintf(fout, "%d\n", findPoz(a));
        } else {
            b = readInt(fin);
            if (cer == 0) {
                addBit(a, b);
            } else {
                fprintf(fout, "%d\n", bitSum(b) - bitSum(a - 1));
            }
        }
    }
    fclose(fin);
    fclose(fout);
    return 0;
}