Mai intai trebuie sa te autentifici.
Cod sursa(job #3176987)
Utilizator | Data | 28 noiembrie 2023 10:35:32 | |
---|---|---|---|
Problema | Arbori indexati binar | Scor | 50 |
Compilator | cpp-64 | Status | done |
Runda | Arhiva educationala | Marime | 1.41 kb |
#include <iostream>
#include <fstream>
using namespace std;
#define MaxN 100000
#define LogN 20
int n;
int v[MaxN], aib[MaxN];
int lsbit (int x)
{
return x & -x;
}
int query(int x)
{
int res=0;
while(x>0)
{
res+=aib[x];
x-=lsbit(x);
}
return res;
}
void build()
{
int i;
for(i=1; i<=n; i++)
{
aib[i]+=v[i];
if(i+lsbit(i)<=n)
{
aib[i+lsbit(i)]+=aib[i];
}
}
}
void update(int pos, int val)
{
while(pos<=n)
{
aib[pos]+=val;
pos+=lsbit(pos);
}
}
int bsearch(int val)
{
int pos=0, pas, s=0;
pas=1<<LogN;
while(pas)
{
if(pos+pas<=n && s+aib[pos+pas]<=val)
{
pos+=pas;
s+=aib[pos];
}
pas>>=1;
}
if(query(pos)==val) return pos;
return -1;
}
int main()
{
ifstream in("aib.in");
ofstream out("aib.out");
int m, i, type, a, b;
in>>n>>m;
for(i=1; i<=n; i++)
{
in>>v[i];
}
build();
for(i=0; i<m; i++)
{
in>>type>>a;
if(type==0)
{
in>>b;
update(a, b);
}
else if(type==1)
{
in>>b;
out<<query(b)-query(a-1)<<'\n';
}
else
{
out<<bsearch(a)<<'\n';
}
}
return 0;
}