Cod sursa(job #1101597)

Utilizator Mihai_ChihaiMihai Chihai Mihai_Chihai Data 8 februarie 2014 18:56:59
Problema Arbori indexati binar Scor 0
Compilator fpc Status done
Runda Arhiva educationala Marime 1.55 kb
program aib;
var a:array[1..120000] of longint;
    n,m,i,op,x,y,l,r,mid,sum:longint;
    ok:boolean;
procedure update(poz,val:longint);
begin
while (poz<=n) do begin
a[poz]:=a[poz]+val;
poz:=poz+(poz and (-poz));
end;
end;
function suma(poz:longint):longint;
begin
suma:=0;
while (poz<>0) do begin
    inc (suma,a[poz]);
    poz:=poz-(poz and (-poz));
    end;
end;
begin
assign(input,'aib.in'); reset(input);
assign(output,'aib.out'); rewrite(output);
readln(n,m);
for i:=1 to n do begin
                read(x);
                update(i,x);
                end;
for i:=1  to m do begin
        read(op);
        if op=0 then begin
                        readln(x,y);
                        update(x,y);
                      end
          else if op=1 then begin
                        readln(x,y);
                        writeln(suma(y)-suma(x-1));
                        end
         else begin
             readln(x);
             l:=1;
             r:=n;

             ok:=false;
             while (l<=r) and (not ok) do begin
                        mid:=(l+r)div 2;
                        sum:=suma(mid);
                        if sum=x then begin
                                        ok:=true;
                                        break;
                                        end
                                 else if sum>x then r:=mid-1
                                     else l:=mid+1;
                        end;
             writeln(mid);
             end;
          end;
close(output);
end.