Cod sursa(job #337171)

Utilizator crisojogcristian ojog crisojog Data 2 august 2009 20:00:41
Problema Arbori indexati binar Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 1.77 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 sum)  
{  
    int pos=n+1,b;  
    int st=0,dr=n+1;  
    b=n;
    s=query(b);
	if(s==sum) pos=n;  
    while(b)  
    {  
		b=(st+dr)>>1;  
        s=query(b);  
        if(s>sum)  
        {  
            if(dr>b) dr=b;  
            b--;  
        }  
        else if (s==sum) pos=minim(pos,b),dr=b,b--;  
        else  
        {  
            if (st<b) st=b;  
            b++;
        }  
        if(b<=st) break;  
        if(b>=dr) break;  
    }  
    if(pos==n+1) return -1;  
    return pos;  
}  

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;
}