C - A Simple Problem with Integers
POJ - 3468You 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.
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.
You need to answer all Q commands in order. One answer in a line.
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 4Sample Output
4 55 9 15Hint
The sums may exceed the range of 32-bit integers.
线段树延迟标记模板题
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int maxn=1e5+5;
long long sum[maxn*4];
long long lazy[maxn*4];
long long c;
int n,m,x,y;
string M;
void pushup(int rt)
{
sum[rt]=sum[rt*2]+sum[rt*2+1];
}
void pushdown(int rt,int len)
{
if(lazy[rt])
{
lazy[rt*2]+=lazy[rt];
lazy[rt*2+1]+=lazy[rt];
sum[rt*2]+=lazy[rt]*(len-len/2);
sum[rt*2+1]+=lazy[rt]*(len/2);
lazy[rt]=0;
}
}
void build(int l,int r,int rt)
{
lazy[rt]=0;
if(l==r)
{
scanf("%lld",&sum[rt]);
return;
}
int mid=(l+r)/2;
build(l,mid,2*rt);
build(mid+1,r,2*rt+1);
pushup(rt);
}
void update(int l,int r,int rt)
{
if(x<=l&&r<=y)
{
lazy[rt]+=c;
sum[rt]+=c*(r-l+1);
return;
}
pushdown(rt,r-l+1);
int mid=(l+r)/2;
if(x<=mid) update(l,mid,2*rt);
if(y>mid) update(mid+1,r,2*rt+1);
pushup(rt);
}
long long query(int l,int r,int rt)
{
if(x<=l&&r<=y)
{
return sum[rt];
}
pushdown(rt,r-l+1);
int mid=(l+r)/2;
long long left=0;
long long right=0;
if(x<=mid) left+=query(l,mid,2*rt);
if(y>mid) right+=query(mid+1,r,2*rt+1);
return left+right;
}
int main()
{
while(~scanf("%d%d",&n,&m))
{
build(1,n,1);
while(m--)
{
cin>>M;
if(M=="Q")
{
scanf("%d%d",&x,&y);
printf("%lld\n",query(1,n,1));
}
else
{
scanf("%d%d%lld",&x,&y,&c);
update(1,n,1);
}
}
}
return 0;
}