利用差分,先得到一个差分序列(如:(1,2,3,5)的差分序列为(1,1,1,2))
当[i,j]段中所有数均加上数m时,在差分序列的i位置加上m,在j+1位置减去m即可
求和利用树状数组
以下是pascal程序:
var a,fai:array[0..1000] of longint; c:char; n,i,x,y,f,m:longint; function lowbit(x:longint):longint; begin lowbit:=x and (-x); end; procedure modify(k,d:longint); begin while k<=n do begin fai[k]:=fai[k]+d; k:=k+lowbit(k); end; end; function sum(x:longint):longint; begin sum:=0; while x>0 do begin sum:=sum+fai[x]; x:=x-lowbit(x); end; end; begin readln(n); for i:=1 to n do begin read(a[i]); modify(i,a[i]-a[i-1]); end; readln(m); for i:=1 to m do begin read(c); if c='C' then begin readln(x,y,f); modify(x,f); modify(y+1,-f); end; if c='Q' then begin readln(x); writeln(sum(x)); end; end; readln; end.
时间: 2024-10-17 10:24:45