A Simple Problem with Integers(线段树成段更新)


Link:http://poj.org/problem?id=3468


A Simple Problem with Integers
Time Limit: 5000MS   Memory Limit: 131072K
Total Submissions: 68421   Accepted: 21091
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

Hint

The sums may exceed the range of 32-bit integers.

Source

POJ Monthly--2007.11.25, Yang Yi


AC  code:

#include<iostream>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<queue>
#include<cstdio>
#define LL long long
#define MAXN  100010
using namespace std;
struct node{
	int l,r;
	LL tag;//注意:tag也必须是long long,不能int!!!否则wa!!!
	LL  sum;
}tree[MAXN*4];
int a[MAXN];
void build(int rt,int l,int r)
{
	tree[rt].l=l;
	tree[rt].r=r;
	tree[rt].tag=0;
	if(l==r)
	{
		tree[rt].sum=a[l];
		return;
	}
	int mid=(l+r)/2;
    build(rt*2,l,mid);
    build(rt*2+1,mid+1,r);
    tree[rt].sum=tree[rt*2].sum+tree[rt*2+1].sum;	
}
void update(int rt,int ul,int ur,LL v)
{
	if(tree[rt].l==ul&&tree[rt].r==ur)
	{
		tree[rt].tag+=v;
		return;
	}
	tree[rt].sum+=v*(ur-ul+1);
	int mid=(tree[rt].l+tree[rt].r)/2;
	if(mid>=ur) update(rt*2,ul,ur,v);
	else if(mid<ul) update(rt*2+1,ul,ur,v);
	else
	{
		update(rt*2,ul,mid,v);
		update(rt*2+1,mid+1,ur,v);
	}
}
LL query(int rt,int l,int r)
{
	if(tree[rt].l==l&&tree[rt].r==r)
	{
		return tree[rt].sum+(r-l+1)*tree[rt].tag;
	}
	tree[rt].sum+=(tree[rt].r-tree[rt].l+1)*tree[rt].tag;
	int mid=(tree[rt].l+tree[rt].r)/2;
	update(rt*2,tree[rt].l,mid,tree[rt].tag);
	update(rt*2+1,mid+1,tree[rt].r,tree[rt].tag);
	tree[rt].tag=0;
	if(r<=mid) return query(rt*2,l,r);
	else if(l>mid)  return query(rt*2+1,l,r);
	else{
		return query(rt*2,l,mid)+query(rt*2+1,mid+1,r);
	}
}
int main()
{
	int n,q,x,y,z,i;
	char ch;
	while(scanf("%d%d",&n,&q)!=EOF)
	{
		for(i=1;i<=n;i++)
		{
			scanf("%d",&a[i]);
		}
		build(1,1,n);
		while(q--)
		{
			cin>>ch;
			if(ch=='Q')
			{
				scanf("%d%d",&x,&y);
				
				printf("%I64d\n",query(1,x,y));
			}
			else
			{
				scanf("%d%d%d",&x,&y,&z);
				update(1,x,y,z);
			}
		}
	}
	return 0;
}


你可能感兴趣的:(算法,ACM)