Cod sursa(job #337173)

Utilizator crisojogcristian ojog crisojog Data 2 august 2009 20:06:33
Problema Arbori indexati binar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.62 kb
#include <stdio.h>  
#include <fstream>  
using namespace std; 
int n,m,t,c,s;  
int arb[100010];  
 
inline int minim(int a, int b)
{
	if(a>b) return b;
	return a;
}

void update(int poz, int val)  
{  
     c = 0;  
     while(poz<=n)  
     {  
           arb[poz]+=val;  
           while(!(poz&(1<<c))) c++;  
           poz+=(1<<c);  
           c+=1;  
     }  
}  

int query(int poz)  
{  
    c=0;
	s=0;  
    while(poz>0)  
    {  
		s+=arb[poz];  
        while(!(poz&(1<<c))) c++;  
        poz-=(1<<c);  
        c+=1;  
    }  
      
    return s;  
}  

int search(int val)  
{  
    int i, step;  
      
    for(step=1;step<n;step=step<<1 );   
    for(i=0;step;step=step>>1)  
    {  
         if(i+step<=n)  
         {  
            if(val>=arb[i+step])   
            {  
                i+=step;
				val-=arb[i];  
                if(!val) return i;  
            }  
         }  
    }  
      
    return -1;  
}  

int main()  
{  
    freopen("aib.in","r",stdin);  
    freopen("aib.out","w",stdout);  
    
	int cod,x,y;
	  
    scanf("%d%d", &n, &m);  
    for(int i=1;i<=n;++i)  
    {  
        scanf("%d", &t);  
        update(i,t);  
    }  
      
    for ( ; m; m-- )  
    {  
        scanf("%d", &cod);  
        if (cod<2)  
        {  
             scanf("%d%d", &x, &y);  
             if (cod==0 ) update(x,y);  
             else printf("%d\n", query(y)-query(x-1));  
        }  
        else  
        {  
            scanf("%d", &x);  
            printf("%d\n", search(x));  
        }  
    }  
	return 0;
}