http://poj.org/problem?id=3468
Description
You have N integers, A1, A2, ... , AN. You need to deal with two kinds of operations. One type of operation is to add some given number to each number in a given interval. The other is to ask for the sum of numbers in a given interval.
Input
The first line contains two numbers N and Q. 1 ≤ N,Q ≤ 100000.
The second line contains N numbers, the initial values of A1, A2, ... , AN. -1000000000 ≤ Ai ≤ 1000000000.
Each of the next Q lines represents an operation.
"C a b c" means adding c to each of Aa, Aa+1, ... , Ab. -10000 ≤ c ≤ 10000.
"Q a b" means querying the sum of Aa, Aa+1, ... , Ab.
Output
You need to answer all Q commands in order. One answer in a line.
Sample Input
10 5 1 2 3 4 5 6 7 8 9 10 Q 4 4 Q 1 10 Q 2 4 C 3 6 3 Q 2 4
Sample Output
4 55 9 15
Hint
几点注意:1. 线段树里面sum值和flag值要用long long
2. 输入时要有一个getchar()取出回车符
#include <stdio.h>
#include <string.h>
#include <iostream>
using namespace std;
typedef long long LL;
const int N=100005;
LL a[N];
struct SegementTree
{
struct Tree
{
int l,r;
LL sum;
LL flag;
}tree[N*4];
void push_up(int root)
{
tree[root].sum=tree[root<<1].sum+tree[root<<1|1].sum;
}
void push_down(int root)
{
if(tree[root].flag!=0)
{
tree[root<<1].flag+=tree[root].flag;
tree[root<<1|1].flag+=tree[root].flag;//左右子树做标记
tree[root<<1].sum+=(tree[root<<1].r-tree[root<<1].l+1)*tree[root].flag;
tree[root<<1|1].sum+=(tree[root<<1|1].r-tree[root<<1|1].l+1)*tree[root].flag;
tree[root].flag=0;//该节点的子树已经更新完毕,其取消标记
}
}
void build(int root,int L,int R)
{
tree[root].l=L;
tree[root].r=R;
tree[root].flag=0;
if(tree[root].l==tree[root].r)
{
tree[root].sum=a[L];
return;
}
int mid=L+(R-L)/2;
build(root<<1,L,mid);
build(root<<1|1,mid+1,R);
push_up(root);
}
void update(int root,int L,int R,int k)
{
if(L<=tree[root].l&&tree[root].r<=R)
{
tree[root].flag+=k;
tree[root].sum+=(tree[root].r-tree[root].l+1)*k;
return;
}
push_down(root);//本次更新到该区间,要把上次更新的区间值向其左右子树更新上次的值
int mid=tree[root].l+(tree[root].r-tree[root].l)/2;
if(L<=mid)
update(root<<1,L,R,k);
if(mid<R)
update(root<<1|1,L,R,k);
push_up(root);
}
LL query(int root,int L,int R)
{
if(L<=tree[root].l&&tree[root].r<=R)
{
return tree[root].sum;
}
push_down(root);//查询到该区间要把上次更新的值向其左右子树进行更新,保证最后统计的数是全部更新后的值
LL sum=0;
int mid=tree[root].l+(tree[root].r-tree[root].l)/2;
if(L<=mid)
sum+=query(root<<1,L,R);
if(mid<R)
sum+=query(root<<1|1,L,R);
return sum;
}
}tr;
int main()
{
int n,m;
while(~scanf("%d%d",&n,&m))
{
for(int i=1;i<=n;i++)
scanf("%lld",&a[i]);
tr.build(1,1,n);
char c;
int x,y,k;
for(int i=0;i<m;i++)
{
scanf("\n%c",&c);
if(c=='Q')
{
scanf("%d%d",&x,&y);
printf("%lld\n",tr.query(1,x,y));
}
else if(c=='C')
{
scanf("%d%d%d",&x,&y,&k);
tr.update(1,x,y,k);
}
}
}
return 0;
}