Cod sursa(job #2900921)

Utilizator petru-robuRobu Petru petru-robu Data 12 mai 2022 15:24:38
Problema Arbori indexati binar Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.16 kb
#include <bits/stdc++.h>
#define lsb(x) x & (-x)

using namespace std;
ifstream fin ("aib.in");
ofstream fout ("aib.out");

#define N 100001

int aib[N], n, q, x;

void update (int pos, int val)
{
    for (int i = pos; i <= n; i += lsb(i))
        aib[i] += val;
}

int query (int pos)
{
    int s = 0;
    for (int i = pos; i >= 1; i -= lsb(i))
        s += aib[i];
    return s;
}

int binary_search(int x)
{
	int st = 1, dr = n;
	while (st <= dr)
  {
		int mij = (st + dr) / 2;
		if (query(mij) < x)
			st = mij + 1;
		else
			dr = mij - 1;
	}
	return st;
}

struct Query
{
    int ind;
    int st, dr;
} qu;


int main()
{
    fin>>n>>q;

    for(int i=1; i<=n; i++)
    {
        fin>>x;
        update(i, x);
    }

    for(int i=1; i<=q; i++)
    {
        fin >> qu.ind >> qu.st;
        if (!qu.ind)
        {
            fin>>qu.dr;
            update (qu.st, qu.dr);
        }
        else if (qu.ind == 1)
        {
            fin >> qu.dr;
            fout<< query(qu.dr) - query(qu.st-1) <<'\n';
        }
        else
        {
            fout << binary_search(qu.st) <<'\n';
        }

    }

}