Cod sursa(job #3242633)

Utilizator Robert_MitriRobert Mitri Robert_Mitri Data 12 septembrie 2024 21:03:48
Problema Arbori indexati binar Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.47 kb
#include <fstream>
#include <vector>
#include <algorithm>
using namespace std;
ifstream fin("aib.in");
ofstream fout("aib.out");

const int nmax = 100000;

int n,m;


long long as[nmax + 5];

void update(int poz,int val)
{
    for(; poz<=n; poz+=(poz&(-poz))) as[poz] += val;
}
long long query(int poz)
{
    long long s=0;
    for(; poz>0; poz-=(poz&(-poz)))
        s+=as[poz];
    return s;
}

int search_sum(long long sum)
{
    long long val = 0;
    int mask =0;
    int step = 0;
    for(step=1; step<n; step<<=1);
    for(; step>0; step>>=1)
    {
        if (mask+step<=n)
        {
            if(val + as[mask + step]<sum)
                val+=as[mask + step],mask+=step;
            else if(val + as[mask + step] == sum)
                return mask + step;
        }
    }
    return -1;
}




int main()
{
    fin>>n>>m;
    for(int i=1; i<=n; i++)
    {
        int x;
        fin>>x;
        update(i,x);
    }
    for(int i=1; i<=m; i++)
    {
        int t;
        fin>>t;
        if(t==0)
        {
            long long a,b;
            fin>>a>>b;
            update(a,b);
        }
        else if(t==1)
        {
            long long a,b;
            fin>>a>>b;
            long long sol = query(b);
            if(a!=1) sol-=query(a-1);
            fout<<sol<<'\n';
        }
        else
        {
            long long a;
            fin>>a;
            fout<<search_sum(a)<<'\n';
        }
    }
}