Cod sursa(job #293023)

Utilizator jeanFMI - Petcu Ion Cristian jean Data 31 martie 2009 21:31:22
Problema Arbori indexati binar Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 1.28 kb
#include<fstream>
using namespace std;
int v[100010],m,n,i,j,poz,x,st,dr,S,op;
int minim (int a,int b)
 { if(a<b) return a;
   return b;
 }
void update(int poz,int val)

  { int k=0;

      while(poz<=n)
       {v[poz]+=val;
        while(!(poz&(1<<k))) k++;
        poz+=(1<<k);
        k++;
       }
  }
int query (int poz)
 { int k=0,s=0;

    while(poz>0)

     { s+=v[poz];
       while(!(poz&(1<<k))) k++;
       poz-=(1<<k);
       k++;
     }
   return s;
 }

int search (int sum)

 { int poz=n+1,B=n,s=0,d=n+1;

   S=query(B);

   if(S==sum) poz=n;

   while(B)

    { B=(s+d)>>1;
      S=query(B);

      if(S>sum)

        { if(d>B) d=B; B--;}


        else if(S==sum) { poz=minim(poz,B); d=B; B--;}


        else  { if(s<B) s=B; B++;}

      if(B<=s) break;
      if(B>=d) break;
    }
  if(poz==n+1) return -1;

  return poz;
}


int main()
{
ifstream f("aib.in");
ofstream g("aib.out");
f>>n>>m;

for(i=1;i<=n;i++)

 { f>>x; update(i,x);}

for(i=1;i<=m;i++)
 { f>>op;

  if(!op) { f>>poz>>x; update(poz,x);}

   else if(op==1)
          { f>>st>>dr;
            g<<query(dr)-query(st-1)<<'\n';}

      else {f>>x; g<<search(x)<<'\n';}
 }
f.close();
g.close();
return 0;
}