Cod sursa(job #484453)

Utilizator cosmyoPaunel Cosmin cosmyo Data 14 septembrie 2010 16:12:44
Problema Arbori indexati binar Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 0.88 kb
#include<fstream.h>
const int NMAX=100005;
int n,m,c[NMAX],a,b,r,x[NMAX];
int poz(int x)
{return (x&(x-1))^x;}
int suma(int k)
{int su=0;
 for(;k>=1;k-=poz(k))
	su+=c[k];
 return su;
}
void update(int k,int x)
{for(;k<=n;k+=poz(k))
	c[k]+=x;
}
int sum(int s)
{int rez=n+1,pow,r=0,sum=s;
 pow=1;
  while(pow<=n)
	  pow*=2;
  pow/=2;
  while(pow)
  { if((r+pow)<=n) if(c[r+pow]>=s){rez=r+pow;}else{r+=pow;s-=c[r+pow];}
    pow/=2;
  }
  if(rez==n+1||suma(rez)!=sum)
	  return -1;
  else
	  return rez;
}
int main()
{ifstream fin("aib.in");
 ofstream fout("aib.out");
  fin>>n>>m;
 int i;
   for(i=1;i<=n;++i)
	   fin>>x[i];
  for(i=1;i<=m;++i)
	  {fin>>r;
          if(r!=2)
		 {fin>>a>>b;
		  if(r==0)
			 update(a,b);
		  else
			  fout<<suma(b)-suma(a-1)<<'\n';
		 }
		 else
		 {fin>>a;fout<<sum(a)<<'\n';}
}
 fin.close();
 fout.close();
 return 0;
}