线段树(区间修改,区间查询)

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
思路
感觉线段树最重要的就是add,和query这两个函数了,这道题是区间查询,区间修改,只要区间的范围正确,注意一下,标记,着种题就很简单了
代码

#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
int val=0,date[100023];
long long sum;
struct qwe
{
	long long lazy,sum;
	int l,r; 
}node[400023];
void build(int o,int l,int r)
{
	node[o].l=l;
	node[o].r=r;
	node[o].lazy=0;
	if(l==r)
	{
		node[o].sum=date[l];
		return;
	}
	else
	{
		int mid=(node[o].l+node[o].r)/2;
		build(2*o,l,mid);
		build(2*o+1,mid+1,r);
		node[o].sum=node[2*o].sum+node[2*o+1].sum;
	}
}
void olazy(int o)
{
	if(node[o].lazy!=0)//有标记
	{
	//左右儿子加上标记
		node[2*o].lazy+=node[o].lazy;
		node[2*o+1].lazy+=node[o].lazy;
		//左右儿子的区间和加上
		node[2*o].sum+=node[o].lazy*(node[2*o].r-node[2*o].l+1);
		node[2*o+1].sum+=node[o].lazy*(node[2*o+1].r-node[2*o+1].l+1);
        node[o].lazy=0;//用完清零
	}
}
void add(int o,int l,int r)//区间修改,l,r是修改的范围
{
	if(node[o].l==l&&node[o].r==r)
	{
		node[o].lazy+=val;
		node[o].sum+=val*(r-l+1);
		return;
	}
	if(node[o].l==node[o].r)//一个点不是区间
	return;
	olazy(o);
	int mid=(node[o].l+node[o].r)/2;
	if(r<=mid)//在左
	add(2*o,l,r);
	else
	if(l>mid)//在右
	  add(2*o+1,l,r);
	  else
	  {
	  //分段
	  	add(2*o,l,mid);
	  	add(2*o+1,mid+1,r);
	  }
	  node[o].sum=node[2*o].sum+node[2*o+1].sum;
}
long long query(int o,int l,int r)//l,r是修查询范围
{
	if(node[o].l==l&&node[o].r==r)
	return node[o].sum;
	olazy(o);//儿子继续向下标记,如果以前标记了,现在就要向下传递了
	long long res=0;//递归求出和,
	int mid=(node[o].l+node[o].r)/2;
	if(r<=mid)
	res+=query(2*o,l,r);
	else if(l>mid)
	res+=query(2*o+1,l,r);
	else
	{
		res+=query(2*o,l,mid);
		res+=query(2*o+1,mid+1,r);
	}
	return res;
}
int main()
{
	int n,m,i;
	scanf("%d%d",&n,&m);
	for(i=1;i<=n;i++)
	scanf("%d",&date[i]);
	build(1,1,n);
	char z;
	int x,y,k;
	while(m--)
	{
		getchar();//吸收换行
		scanf("%c",&z);
	//	printf("%c>>>>\n",z);
		 if(z=='Q')
		 {
		 	scanf("%d %d",&x,&y);
		 	printf("%lld\n",query(1,x,y));//注意要用long long 数据很大
		 }
		 else
		 {
		 	scanf("%d %d %d",&x,&y,&val);
		 	add(1,x,y);
		 }
	}
	return 0;
 } 
已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 数字20 设计师:CSDN官方博客 返回首页