题目链接:POJ3468
Time Limit: 5000MS | Memory Limit: 131072K | |
Total Submissions: 90092 | Accepted: 28052 | |
Case Time Limit: 2000MS |
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
题目分析:线段树的整段查询,hint里说貌似int不够用,这里注意改称long long后懒惰数组的值也要long long型,连续加法或连续减法也可能超int。还有这里判断pushdown需要让懒惰数组不等于0,因为有可能出现负数。输入字符用%s比%c要快(很多),原因未知。
//
// main.cpp
// POJ3468
//
// Created by teddywang on 16/5/24.
// Copyright © 2016年 teddywang. All rights reserved.
//
#include <iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define N 100010
#define ll long long
ll sum[N<<2],lazy[N<<2];
int n,m;
void pushup(int rt)
{
sum[rt]=sum[rt<<1]+sum[rt<<1|1];
}
void build(int l,int r,int rt)
{
lazy[rt]=0;
if(l==r)
{
scanf("%lld",&sum[rt]);
return;
}
int m=(l+r)>>1;
build(lson);
build(rson);
pushup(rt);
}
void pushdown(int rt,int m)
{
if(lazy[rt]!=0)
{
lazy[rt<<1]+=lazy[rt];
lazy[rt<<1|1]+=lazy[rt];
sum[rt<<1]+=lazy[rt]*(m-(m>>1));
sum[rt<<1|1]+=lazy[rt]*(m>>1);
lazy[rt]=0;
}
}
void update(int v,int l1,int r1,int l,int r,int rt)
{
if(l1<=l&&r<=r1)
{
sum[rt]+=(ll)v*(r-l+1);
lazy[rt]+=v;
return ;
}
pushdown(rt,r-l+1);
int m=(l+r)>>1;
if(l1<=m) update(v,l1,r1,lson);
if(r1>m) update(v,l1,r1,rson);
pushup(rt);
}
ll query(int l1,int r1,int l,int r,int rt)
{
if(l1<=l&&r<=r1)
return sum[rt];
int m=(l+r)>>1;
pushdown(rt,r-l+1);
ll ans=0;
if(l1<=m) ans+=query(l1,r1,lson);
if(r1>m) ans+=query(l1,r1,rson);
pushup(rt);
return ans;
}
int main()
{
while(cin>>n>>m)
{
build(1,n,1);
for(int i=0;i<m;i++)
{
char c;
cin>>c;
if(c=='Q')
{
int l1,r1;
scanf("%d%d",&l1,&r1);
printf("%lld\n",query(l1,r1,1,n,1));
}
else
{
int l1,r1,v;
scanf("%d%d%d",&l1,&r1,&v);
update(v,l1,r1,1,n,1);
}
}
}
}