Cod sursa(job #1211544)

Utilizator RusuAlexeiRusu Alexei RusuAlexei Data 22 iulie 2014 20:03:52
Problema Arbori indexati binar Scor 100
Compilator fpc Status done
Runda Arhiva educationala Marime 1.93 kb
program aib;
  var bufin,bufout:array[0..100000]of byte;
      m,n,i,op,x,y,pow:longint;
      a:array [1..100000] of longint;

procedure build;

  begin
    pow:=2;
    while pow<=n do
      begin
        i:=pow;
        while i<=n do
          begin
            a[i]:=a[i]+a[i-pow shr 1];
            i:=i+pow;
          end;
        pow:=pow shl 1;
      end;
    pow:=pow shr 1;
  end;

procedure update(pos,val:longint);
  var z:longint;
  begin
    z:=pos;
    while z<=n do
      begin
        a[z]:=a[z]+val;
        z:=z+z and-z;
      end;
  end;

function sum(l,r:longint):longint;
  var z,sum1,sum2:longint;
  begin
    z:=l-1;sum1:=0;sum2:=0;
    while z>0 do
      begin
        sum1:=sum1+a[z];
        z:=z-z and -z;
      end;
    z:=r;
    while z>0 do
      begin
        sum2:=sum2+a[z];
        z:=z-z and -z;
      end;
    sum:=sum2-sum1;
  end;

function search(k:longint):longint;
  var z,s,u:longint;
  begin
    s:=k;
    if (pow=n)and(a[pow]=s) then search:=n else
      begin
        z:=pow;
        while (a[z]<>s)and(z and -z<>1) do
          begin
            if a[z]>s then z:=z-(z and -z)shr 1 else
              begin
                s:=s-a[z];
                u:=(z and -z)shr 1;
                while z+u>n do u:=u shr 1;
                z:=z+u;
              end;
          end;
        if a[z]<>s then search:=-1 else search:=z;
      end;

  end;

begin
  assign(input,'aib.in');
  reset(input);
  settextbuf(input,bufin);
  assign(output,'aib.out');
  rewrite(output);
  settextbuf(output,bufout);

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

  build;

  for i:=1 to m do
    begin
      read(op,x);
      if op=2 then writeln(search(x))
              else begin
                read(y);
                if op=0 then update(x,y)
                        else writeln(sum(x,y));
              end;
    end;
  close(output);
end.