Problem
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
The sums may exceed the range of 32-bit integers.
题意:
给你n个整数和q次询问,你需要区间求和和区间修改
Q 表示询问区间a到b的和;C 表示对区间a到b的每个值加一
思路:
模板题
代码:
#include
#include
#include
using namespace std;
const long long maxn=100005;
long long a[maxn];
struct Node
{
long long l,r,data;
long long len,lazy;//lazy懒标记,len记录区间长度,方便求和
} node[maxn*4];
void build(long long l, long long r, long long root) //创建线段树
{
node[root].l=l, node[root].r=r;
node[root].len=r-l+1;
node[root].lazy=0;
if(l==r)//叶子结点,直接赋值
{
node[root].data=a[l];
return;
}
long long mid=(l+r)/2;
build(l,mid,root<<1);//递归构造左儿子结点
build(mid+1,r,root<<1|1);//递归构造右儿子结点
node[root].data = node[root<<1].data + node[root<<1|1].data;//更新父结点
}
void pushDown(long long root)//更新懒标记
{
if(node[root].lazy)
{
node[root*2].lazy += node[root].lazy;
node[root*2+1].lazy += node[root].lazy;
node[root*2].data += node[root*2].len * node[root].lazy;
node[root*2+1].data += node[root*2+1].len * node[root].lazy;
node[root].lazy=0;
}
}
void rangeUpdate(long long l,long long r,long long val,long long root)//区间更新
{
long long L=node[root].l;
long long R=node[root].r;
if(l<=L&&R<=r)//当前结点的区间真包含于待查询区间,更新结点信息
{
node[root].lazy+=val;
node[root].data+=node[root].len*val;
}
else
{
pushDown(root);//关键,查询lazy标记,更新子树
long long m=(L+R)/2;
if(l<=m)
rangeUpdate(l,r,val,root<<1);//左子树和要更新区间有交集
if(r>m)
rangeUpdate(l,r,val,root<<1|1);//右子树和要更新区间有交集
node[root].data=node[root<<1].data+node[root<<1|1].data;
}
}
long long rangeQueries(long long l,long long r,long long root)//区间查询
{
long long L=node[root].l;
long long R=node[root].r;
if(l<=L&&R<=r)
{
return node[root].data;//当前结点的区间真包含于待查询区间,返回结点信息
}
else
{
pushDown(root);//查询lazy标记,更新子树
long long m=(L+R)/2;
if(r<=m)
return rangeQueries(l,r,root<<1);//要更新区间在左子树
else if(l>m)
return rangeQueries(l,r,root<<1|1);//要更新区间在右子树
else
return rangeQueries(l,r,root<<1)+rangeQueries(l,r,root<<1|1);//要更新区间在左右子树
}
}
int main()
{
int N,Q;
scanf("%d%d",&N,&Q);
for(int i=1; i<=N; i++)
scanf("%lld",&a[i]);
build(1,N,1);
for(int i=1; i<=Q; i++)
{
char ch;
long long a,b,c;
scanf(" %c",&ch);
if(ch=='Q')
{
scanf("%lld%lld",&a,&b);
printf("%lld\n",rangeQueries(a,b,1));
}
else if(ch=='C')
{
scanf("%lld%lld%lld",&a,&b,&c);
rangeUpdate(a,b,c,1);
}
}
return 0;
}
推荐一个:
线段树入门详解