bzoj 3155 树状数组

题意:对序列ai维护一个前缀和序列Si,再对Si维护一个前缀和序列Ti,支持两种操作:

(1)修改ai的值

(2)查询Ti

∑((x - i + 1) * ai) = ∑( (n - i + 1) * ai ) - (n - x) * ∑ai

分别用两个树状数组维护

var
        n,m             :longint;
        i               :longint;
        ch              :char;
        x,y             :int64;
        c1,c2,a         :array[0..100010] of int64;
function lowbit(x:longint):longint;
begin
   exit(x and (-x));
end;

procedure add(t,x,y:int64);
begin
   if t=1 then
   begin
      while (x<=n) do
      begin
         inc(c1[x],y);
         inc(x,lowbit(x));
      end;
   end else
   begin
      while (x<=n) do
      begin
         inc(c2[x],y);;
         inc(x,lowbit(x));
      end;
   end;
end;

function sum(t,x:longint):int64;
var
        ans:int64;
begin
   ans:=0;
   if t=1 then
   begin
      while (x>0) do
      begin
         inc(ans,c1[x]);
         dec(x,lowbit(x));
      end;
   end else
   begin
      while (x>0) do
      begin
         inc(ans,c2[x]);
         dec(x,lowbit(x));
      end;
   end;
   exit(ans);
end;

begin
   read(n,m);
   for i:=1 to n do
   begin
      read(a[i]);
      add(1,i,a[i]);
      add(2,i,(n-i+1)*a[i]);
   end;
   readln;
   for i:=1 to m do
   begin
      read(ch);
      if (ch='Q') then
      begin
         read(ch,ch,ch,ch);read(x);readln;
         writeln(sum(2,x)-(n-x)*sum(1,x));
      end else
      begin
         read(ch,ch,ch,ch,ch);
         read(x,y);readln;
         add(1,x,y-a[x]);
         add(2,x,(n-x+1)*(y-a[x]));
         a[x]:=y;
      end;
   end;
end.
——by Eirlys

你可能感兴趣的:(树状数组,bzoj)