Cod sursa(job #1350029)

Utilizator Pintilie_AndreiFII-Pintilie Andrei Pintilie_Andrei Data 20 februarie 2015 17:00:03
Problema Arbori indexati binar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.27 kb
#include <iostream>
#include <fstream>
#define N 100004
using namespace std;
int a[N];
int n,m;
void Update(int poz,int x)
{
    while(poz<=n)
    {
        a[poz]+=x;
        poz+=(poz & (-poz));
    }
}
int Query(int poz)
{
    int s=0;
    while(poz>0)
    {
        s+=a[poz];
        poz-=(poz & (-poz));
    }
    return s;
}
int Search(int x)
{
    int st,dr,mij,sol,nr;
    sol=-1;
    st=1;
    dr=n;
    while(st<=dr)
    {
        mij=(st+dr)/2;
        nr=Query(mij);
        if(x==nr)
        {
            sol=mij;
            dr=mij-1;
        }
        else
        if(nr<x) st=mij+1;
        else dr=mij-1;
    }
    return sol;
}
int main()
{
    ifstream fin("aib.in");
    ofstream fout("aib.out");
    fin>>n>>m;
    int i,x,op,y,nr;
    for(i=1; i<=n; i++)
    {
        fin>>x;
        Update(i,x);
    }
    for(i=1; i<=m; i++)
    {
        fin>>op;
        if(!op)
        {
            fin>>x>>y;
            Update(x,y);
        }
        else if(op==1)
        {
            fin>>x>>y;
            nr=Query(y)-Query(x-1);
            fout<<nr<<"\n";
        }
        else
        {
            fin>>x;
            nr=Search(x);
            fout<<nr<<"\n";
        }
    }
    return 0;
}