Cod sursa(job #2784170)

Utilizator Vlad_AnicaAnica-Popa Vlad-Ioan Vlad_Anica Data 15 octombrie 2021 23:28:44
Problema Arbori indexati binar Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.45 kb
#include <iostream>
#include <stdio.h>

using namespace std;
const int NMAX = 100000;

void update(int pos, int val);
int query(int pos);

int aib[NMAX + 1], n;

int main()
{
    int type, i, lo, hi, step, pos, m, val;
    FILE *fin = fopen("aib.in", "r");
    FILE *fout = fopen("aib.out", "w");
    fscanf(fin, "%d%d", &n, &m);

    for (i = 0; i < n; i++)
    {
        fscanf(fin, "%d", &val);
        update(i + 1, val);
    }

    for (i = 0; i < m; i++)
    {
        fscanf(fin, "%d", &type);
        if (type == 1)
        {
            fscanf(fin, "%d%d", pos, val);
            update(pos, val);
        }
        else if (type == 2)
        {
            fscanf(fin, "%d%d", &lo, &hi);
            fprintf(fout, "%d\n", query(hi) - query(lo - 1));
        }
        else
        {
            fscanf(fin, "%d", &val);
            step = 1 << 16, pos = 0;
            while (step)
            {
                if (step + pos <= n && query(pos + step) < val)
                    pos += step;
                step >>= 1;
            }
            fprintf(fout, "%d\n", pos + 1);
        }
    }
    fclose(fin);
    fclose(fout);

    return 0;
}

void update(int pos, int val)
{
    while (pos <= n)
    {
        aib[pos] += val;
        pos += (pos & -pos);
    }
}
int query(int pos)
{
    int s = 0;
    while (pos)
    {
        s += aib[pos];
        pos -= (pos & -pos);
    }
    return pos;
}