POJ 3468:A Simple Problem with Integers(线段树应用之:区间更新,区间查询)
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
The sums may exceed the range of 32-bit integers.
题解:线段树应用之区间更新,区间查询
做了几道简单的点修改,区间查询的线段树题后,开始尝试线段树比较难的区间更新,如果一直更新的叶子结点的话,其时间复杂度也就会变得不那么乐观,线段树这一数据结构优点也就没那么明显了,于是采用lazy标记
刚开始还不太会,参考的别人的代码:https://blog.csdn.net/qq_40604099/article/details/82594966
代码如下:
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
#define ll long long
const int maxn=100010;
/**结点结构*/
struct Node
{
int L,R; //左右端点
ll v; //值
ll len; //区间长度
int lazy; //lazy标记
};
Node tree[4*maxn]; //用数组表示线段树
ll a[maxn]; //要储存的数据
/**建立线段树,并附初值*/
void build_Tree(int root,int L,int R)
{
tree[root].L=L;
tree[root].R=R;
tree[root].len=R-L+1;
tree[root].lazy=0;
if(L==R)
{
tree[root].v=a[L];
return ;
}
int mid=(tree[root].L+tree[root].R)/2;
build_Tree(2*root,L,mid);
build_Tree(2*root+1,mid+1,R);
tree[root].v=tree[2*root].v+tree[2*root+1].v;
}
/**向下传递lazy标记*/
void pushdown(int root)
{
if(tree[root].lazy)
{
tree[root*2].lazy+=tree[root].lazy;
tree[2*root+1].lazy+=tree[root].lazy;
tree[2*root].v+=tree[2*root].len*tree[root].lazy;
tree[2*root+1].v+=tree[2*root+1].len*tree[root].lazy;
tree[root].lazy=0;
}
}
/**区间更新*/
void update(int root,int s,int e,int c)
{
if(tree[root].L>=s&&tree[root].R<=e)
{
tree[root].v+=c*tree[root].len;
tree[root].lazy+=c;
return ;
}
if(tree[root].L>e||tree[root].R<s)
return;
if(tree[root].lazy)
pushdown(root);
update(2*root,s,e,c);
update(2*root+1,s,e,c);
tree[root].v=tree[2*root].v+tree[2*root+1].v;
}
/**查询*/
ll Query(int root,int s,int e)
{
if(tree[root].L>=s&&tree[root].R<=e)
{
return tree[root].v;
}
if(tree[root].L>e||tree[root].R<s)
return 0;
if(tree[root].lazy)
pushdown(root);
return Query(2*root,s,e)+Query(2*root+1,s,e);
}
int main()
{
int n,q; //表示数的个数以及询问次数
scanf("%d%d",&n,&q);
for(int i=1; i<=n; i++)
scanf("%lld",&a[i]);
build_Tree(1,1,n);
char ch; //表示是询问还是修改操作
int a,b,c;
for(int i=1; i<=q; i++)
{
getchar();
scanf("%c",&ch);
if(ch=='Q')
{
scanf("%d%d",&a,&b);
printf("%lld\n",Query(1,a,b));
}
else
{
scanf("%d%d%d",&a,&b,&c);
update(1,a,b,c);
}
}
return 0;
}