Cod sursa(job #598671)

Utilizator ion_calimanUAIC Ion Caliman ion_caliman Data 26 iunie 2011 17:54:11
Problema Arbori indexati binar Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 1.07 kb
#include <fstream>
using namespace std;
ifstream f("aib.in");
ofstream g("aib.out");

int n,m,i,c,x,y,a[210005],k=1;

void modifica(int poz, int val)
{
    while (poz<=k)
        a[poz]+=val,
        poz+=(poz ^ (poz & (poz-1)));
}

long long suma(int poz)
{
    long long t=0;
    while (poz>0)
    t+=a[poz],
    poz-=(poz ^ (poz & (poz-1)));
    return t;
}
int pozitia(int sum)
{
    long long poz=0,t=1,s=0;
    while (s<sum && poz<n)
    {
        while (poz+t+(t ^ (t & (t-1)))<=n && s+a[poz+t+(t ^ (t & (t-1)))]<=sum)
            t+=(t ^ (t & (t-1)));
        poz+=t;
        s+=a[poz];
        t=1;
    }
    if (s==sum) return poz; else return -1;
}

int main()
{
    f >> n >> m;
    while (k<n) k*=2;
    fill_n(a,k+1,0);
    for (i=1; i<=n; i++)
    {
        f >> c;
        modifica(i,c);
    }

    //for (i=1; i<=k; i++) g << a[i] << ' '; g << endl;

    for (i=0; i<m; i++)
    {
        f >> c;
        if (c==0) f >> x >> y, modifica(x,y); else
        if (c==1) f >> x >> y, g << suma(y)-suma(x-1) << "\n"; else
        f >> x, g << pozitia(x) << "\n";
    }
    return 0;
}