C - A Simple Problem with Integers(懒人标记入门)

 

#include<cstdio>
using namespace std;
const int maxn=1e6+10;
typedef long long ll;
struct node
{
	int l,r;
	ll sum,length,lazy;
}a[maxn*4];
int n,m;
void build(int i,int l,int r)
{
	a[i].l=l,a[i].r=r,a[i].sum=a[i].lazy=0;
	a[i].length=(r-l+1);
	if(l==r)
	{
		scanf("%lld",&a[i].sum);
		return ;
	}
	int mid=(l+r)>>1;
	build(i<<1,l,mid);
	build(i<<1|1,mid+1,r);
	a[i].sum=a[i<<1].sum+a[i<<1|1].sum;
}
void pushdown(int i)
{
	if(a[i].lazy)
	{
		a[i<<1].lazy+=a[i].lazy;
		a[i<<1|1].lazy+=a[i].lazy;
		
		a[i<<1].sum+=a[i<<1].length*a[i].lazy;
		a[i<<1|1].sum+=a[i<<1|1].length*a[i].lazy;
		a[i].lazy=0;
	}
}
ll qu(int i,int l,int r)
{
	if(l<=a[i].l&&a[i].r<=r)
	{
		return a[i].sum;
	}
	pushdown(i);
	int mid=(a[i].l+a[i].r)>>1;
	ll ans=0;
	if(l<=mid) ans+=qu(i<<1,l,r);
	if(r>mid) ans+=qu(i<<1|1,l,r);
	return ans;
}
void up(int i,int l,int r,ll val)
{
	if(l<=a[i].l&&a[i].r<=r)
	{
		a[i].lazy+=val;
		a[i].sum+=a[i].length*val;
		return ;
	}
	pushdown(i);
	int mid=(a[i].l+a[i].r)>>1;
	if(l<=mid) up(i<<1,l,r,val);
	if(r>mid) up(i<<1|1,l,r,val);
	a[i].sum=a[i<<1].sum+a[i<<1|1].sum;
}
int main()
{
	while(~scanf("%d%d",&n,&m))
	{
		build(1,1,n);
		while(m--)
		{
			char s[5];
			scanf("%s",s);
			//printf("a[1].id:%d\n\n",a[1].sum);
			if(s[0]=='Q')
			{
				int x,y;
				scanf("%d%d",&x,&y);
				printf("%lld\n",qu(1,x,y));
			}
			else
			{
				int x,y;
				ll z;
				scanf("%d%d%lld",&x,&y,&z);
				up(1,x,y,z);
			}
		}
	}
}

 

 POJ - 3468 

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 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.

猜你喜欢

转载自blog.csdn.net/qq_41286356/article/details/85946725