Cod sursa(job #1211331)

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


procedure build;
  var i:longint;
  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;
  end;

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

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

function cbin(s:longint):longint;
  var x,y,u:longint;


  begin
    pow:=pow shr 1;
    x:=pow;y:=s;
    if a[n]=y then cbin:=n else
      begin
        while (a[x]<>y)and(x and -x<>1) do
          begin
            if a[x]>y then x:=x-(x and -x)shr 1 else
              begin
                u:=(x and -x)shr 1;
                while x+u>n do u:=u shr 1;
                y:=y-a[x];
                x:=x+u;
              end;
          end;
        cbin:=x;
      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(cbin(x)) else
        begin
          read(y);
          if op=0 then update(x,y)
                  else writeln(qsum(x,y));
        end;
      readln;
    end;
  close(output);
end.