Cod sursa(job #2926265)

Utilizator andreipirjol5Andrei Pirjol andreipirjol5 Data 17 octombrie 2022 16:38:04
Problema Arbori indexati binar Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.63 kb
#include <cstdio>
#include <cmath>

using namespace std;
FILE *fin, *fout;

int n;
const int NMAX = 100000;
int BIT[NMAX + 5], v[NMAX + 5];

void update(int pos, int value)
{
    while(pos <= n)
    {
        BIT[pos] += value;

        pos += (pos & (-pos));
    }
}

int query(int pos)
{
    int ans = 0;

    while(pos > 0)
    {
        ans += BIT[pos];

        pos -= (pos & (-pos));
    }

    return ans;
}

int query2(int value)
{
    int max2 = log2(n), poz_c = 0, sum = 0;

    for(int exp = max2; exp >= 0; exp--)
    {
        int poz_cand = poz_c + (1 << exp);

        if(poz_cand <= n and BIT[poz_cand] + sum <= value)
        {
            sum += BIT[poz_cand];

            poz_c = poz_cand;
        }
    }

    return poz_c;
}

int main()
{
    fin = fopen("aib.in", "r");
    fout = fopen("aib.out", "w");

    int m;
    fscanf(fin, "%d%d", &n, &m);

    for(int i = 1; i <= n; i++)
        fscanf(fin, "%d", &v[i]);

    int op, a, b;

    for(int i = 1; i <= n; i++)
        update(i, v[i]);

    /*for(i = 1; i <= n; i++)
        fprintf(fout , "%d " , BIT[i]);

    fprintf(fout , "\n");*/

    for(int i = 1; i <= m; i++)
    {
        fscanf(fin, "%d", &op);

        if(op == 0 or op == 1)
        {
            fscanf(fin, "%d%d", &a, &b);

            if(op == 0)
                update(a, b);
            else fprintf(fout, "%d\n", query(b) - query(a - 1));
        }
        else
        {
            fscanf(fin, "%d", &a);
            fprintf(fout, "%d\n", query2(a));
        }
    }

    fclose(fin);
    fclose(fout);
    return 0;
}