线段树练习五
Description
一行N个方格,开始每个格子里的数都是0。现在动态地提出一些问题和修改:提问的形式是求某一个特定的子区间[a,b]中所有元素的和;修改的规则是指定某一个格子x,加上或者减去一个特定的值A。现在要求你能对每个提问作出正确的回答。1≤N≤100000,提问和修改的总数可能达到100000条。
Input
20 //方格个数
6 //有几组操作
M 1 1 //表示修改,第一个表示格子位置,第二个数表示在原来的基础上加上的数,
M 2 2
M 3 4
M 3 -5
M 6 7
C 2 6 //表示统计 ,第一个数表示起始位置,第二个数表示结束位置
Output
8
分析:
一、线段树
线段树和前面几题一样,只是一个格子进行加减时会对父节点有影响,找到当前格子位置然后往上加就行了。
代码
const
maxn=1000000;
type
tnode=record
a,b,sum:longint;
end;
var
tree:array[0..maxn] of tnode;
x,y,i,j,n,m:longint;
ch:char;
procedure create(p:longint);
var
m:longint;
begin
if tree[p].b-tree[p].a>0 then
begin
m:=(tree[p].a+tree[p].b) div 2;
tree[p*2].a:=tree[p].a;
tree[p*2].b:=m;
tree[p*2+1].a:=m+1;
tree[p*2+1].b:=tree[p].b;
create(p*2);
create(p*2+1);
end;
end;
procedure update(p:longint);
begin
while p>0 do
begin
inc(tree[p].sum,y);
p:=p div 2;
end;
end;
procedure insert(p:longint);
var
m:longint;
begin
if tree[p].b-tree[p].a=0
then begin
update(p);
exit;
end
else begin
m:=(tree[p].a+tree[p].b) div 2;
if x<=m then insert(p*2) else insert(p*2+1);
end;
end;
function count(p:longint):longint;
var
m:longint;
begin
if (x<=tree[p].a) and (y>=tree[p].b)
then exit(tree[p].sum);
m:=(tree[p].a+tree[p].b) div 2;
count:=0;
if x<=m then count:=count+count(p*2);
if y>m then count:=count+count(p*2+1);
end;
begin
readln(m);
tree[1].a:=1;
tree[1].b:=m;
create(1);
readln(n);
for i:=1 to n do
begin
readln(ch,x,y);
if ch='M'
then insert(1)
else writeln(count(1));
end;
end.
二、树状数组
maxn=1000000;
var
a,c:array[0..maxn] of longint;
i,j,k,n,m:longint;
ch:char;
function lowbit(x:longint):longint;
begin
exit(x and(-x));
end;
procedure insert(p,x:longint);
begin
while p<=m do
begin
c[p]:=c[p]+x;
p:=p+lowbit(p);
end;
end;
function count(x:longint):longint;
var
ans:longint;
begin
ans:=0;
while x>0 do
begin
ans:=ans+c[x];
x:=x-lowbit(x);
end;
exit(ans);
end;
begin
readln(m);
readln(n);
for i:=1 to n do
begin
readln(ch,j,k);
if ch='M' then insert(j,k) else writeln(count(k)-count(j-1));
end;
end.