Cod sursa(job #178839)

Utilizator free2infiltrateNezbeda Harald free2infiltrate Data 15 aprilie 2008 11:31:23
Problema Arbori indexati binar Scor 0
Compilator fpc Status done
Runda Arhiva educationala Marime 1.49 kb
program AIB;
var  A : array [1..100000] of integer;
     B : array [1..100000] of longint;
     C : array [0..16] of longint;
     D : array [1..100000] of shortint;
     i,j,n,m,S,p1,p2 : longint;
     x : shortint;
     f,g : text;
function k2c(n:integer):shortint;
begin
k2c := 0;
while n mod 2 = 0 do begin
k2c := k2c+1;
n := n div 2;
end;
end;
procedure build;
var i,j : longint;
begin
for i := 1 to n do begin
B[i] := A[i];
for j := 1 to C[D[i]]-1 do
B[i] := B[i]+A[i-j];
end;
end;

procedure update(poz:longint;val:integer);
begin
while poz<=n do begin
B[poz] := B[poz]+val;
poz := poz+C[D[poz]];
end;
end;

function sum(p:longint):longint;
begin
sum := 0;
while p>0 do begin
sum := sum+B[p];
p := p-C[D[p]];
end;
end;

function po:longint;
var i : longint;
begin
po := -1;

for i := 1 to n do
if sum(i)=S then begin
                 po := i;
                 break;
                 end;
end;


begin
assign(f,'aib.in');
reset(f);
assign(g,'aib.out');
rewrite(g);
readln(f,n,m);

for i := 1 to n do
read(f,A[i]);
readln(f);

C[0] := 1;
for i := 1 to 16 do
C[i] := C[i-1]*2;
for i := 1 to n do
D[i] := k2c(i);

build;

for i := 1 to m do begin
read(f,x);
case x of
0: begin
   readln(f,p1,p2);
   update(p1,p2);
   end;
1: begin
   readln(f,p1,p2);
   writeln(g,sum(p2)-sum(p1-1));
   end;
2: begin
   readln(f,S);
   if S<=B[n] then writeln(g,po)
              else writeln(g,-1);
   end;
end;
end;
close(f);
close(g);
end.