hdu--3468(线段树+lazy思想)

A Simple Problem with Integers
Time Limit: 5000MS   Memory Limit: 131072K
Total Submissions: 82238   Accepted: 25451
Case Time Limit: 2000MS

Description

You have N integers, A1A2, ... , 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 A1A2, ... , AN. -1000000000 ≤ Ai ≤ 1000000000.
Each of the next Q lines represents an operation.
"C a b c" means adding c to each of AaAa+1, ... , Ab. -10000 ≤ c ≤ 10000.
"Q a b" means querying the sum of AaAa+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
 
 
从网上找到了人家对lazy思想的解释,非常容易理解:比如现在需要对[a,b]区间值进行加c操作,那么就从根节点[1,n]开始调用update函数进行操作,如果刚好执行到一个子节点,它的节点标记为rt,这时tree[rt].l == a && tree[rt].r == b 这时我们可以一步更新此时rt节点的sum[rt]的值,sum[rt] += c * (tree[rt].r - tree[rt].l + 1),注意关键的时刻来了,如果此时按照常规的线段树的update操作,这时候还应该更新rt子节点的sum[]值,而Lazy思想恰恰是暂时不更新rt子节点的sum[]值,到此就return,直到下次需要用到rt子节点的值的时候才去更新,这样避免许多可能无用的操作,从而节省时间 。
 
代码如下:
#include<stdio.h>
#include<string.h>
struct stu
{
	int l,r;
	int mid()
	{
		return (l+r)>>1;
	}
};
stu node[1000000];
__int64 sum[1000000];
__int64 add[1000000];
void PUTDOWN(int rt,int m)
{
	if(add[rt])
	{
		add[rt<<1]+=add[rt];
		add[rt<<1|1]+=add[rt];
		sum[rt<<1]+=add[rt]*(m-(m>>1));//算数运算符的优先级大于位运算符 ,竟然在这里错了. 
		sum[rt<<1|1]+=add[rt]*(m>>1);
		add[rt]=0;
	}
}
void PUTUP(int rt)
{
	sum[rt]=sum[rt<<1]+sum[rt<<1|1];
}
void build(int rt,int l,int r)
{
	node[rt].l=l;
	node[rt].r=r;
	add[rt]=0;
	if(l==r)
	{
		scanf("%I64d",&sum[rt]);
		return;
	}
	int m=node[rt].mid();
	build(rt<<1,l,m);
	build(rt<<1|1,m+1,r);//2的倍数的二进制最后一位都为0   
    PUTUP(rt);//一开始每个结点的和 
}
void updata(int rt,int l,int r,int v)
{
	if(node[rt].l==l&&node[rt].r==r)
	{
		add[rt]+=v;
		sum[rt]+=(__int64)v*(r-l+1);
		return;
	}
	PUTDOWN(rt,node[rt].r-node[rt].l+1);
	int m=node[rt].mid();
	if(r<=m)updata(rt<<1,l,r,v);
	else
	{
		if(l>m)updata(rt<<1|1,l,r,v);
		else 
		{
			updata(rt<<1,l,m,v);
			updata(rt<<1|1,m+1,r,v);	
		}
	}
	PUTUP(rt);
}
__int64 query(int rt ,int l,int r)
{
	if(node[rt].l==l&&node[rt].r==r)
	return sum[rt];
	PUTDOWN(rt,node[rt].r-node[rt].l+1);
	int m=node[rt].mid() ;
	if(r<=m) return query(rt<<1,l,r);
	else 
	{
		if(l>m)return query(rt<<1|1,l,r);
		else 
		return query(rt<<1,l,m)+query(rt<<1|1,m+1,r);
	}
}
int main()
{
	int n,m,a,b,v;
	char c;
	while(scanf("%d%d",&n,&m)!=EOF)
	{
		build(1,1,n);
		while(m--)
		{
			getchar();
			scanf("%c%d%d",&c,&a,&b);
			if(c=='Q')
			{
				printf("%I64d\n",query(1,a,b));
			}
			else if(c=='C')
			{
				scanf("%d",&v);
				updata(1,a,b,v);
			}
		}
	}
	return 0;
} 


你可能感兴趣的:(hdu--3468(线段树+lazy思想))