A Simple Problem with Integers
Time Limit: 5000MS Memory Limit: 131072K
Total Submissions: 86938 Accepted: 26990
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
The sums may exceed the range of 32-bit integers.
Source
POJ Monthly–2007.11.25, Yang Yi
思路+题意:
线段数区间修改,求和
代码:
#include<iostream>
#include<stdio.h>
#include<string.h>
#define lson (id*2)
#define rson (id*2+1)
using namespace std;
long long tr[1000000*4+5],lazy[1000000*4+5];
long long ans=0;
int n,m;
void push_up(int id)
{
tr[id]=tr[lson]+tr[rson];
return;
}
void push_down(int id,int l,int mid,int r)
{
if(!lazy[id]) return ;
long long t=lazy[id];
//if(r==5) cout<<tr[rson]<<endl;
lazy[id]=0;
lazy[lson]+=t;
lazy[rson]+=t;
tr[lson]+=(mid-l+1)*t;
tr[rson]+=(r-mid)*t;
return;
}
void build(int id,int l,int r)
{
lazy[id]=0;
if(l==r)
{
scanf("%lld",&tr[id]);
return;
}
int mid=(l+r)>>1;
build(lson,l,mid);
build(rson,mid+1,r);
push_up(id);
}
void add(int id,int L,int R,int l,int r,long long v)
{
if(l>R||r<L||R<L) return ;
if(L>=l&&R<=r)
{
tr[id]+=(R-L+1)*v;
lazy[id]+=v;
return ;
}
int mid=(L+R)>>1;
push_down(id,L,mid,R);
if(l<=mid) add(lson,L,mid,l,r,v);
if(r>=mid+1) add(rson,mid+1,R,l,r,v);
push_up(id);
}
void query(int id,int L,int R,int l,int r)
{
if(l>R||r<L||R<L) return ;
if(L>=l&&R<=r)
{
ans+=tr[id];
return ;
}
int mid=(L+R)>>1;
push_down(id,L,mid,R);
if(l<=mid) query(lson,L,mid,l,r);
if(r>=mid+1) query(rson,mid+1,R,l,r);
}
int main()
{
scanf("%d%d",&n,&m);
build(1,1,n);
char s[2];
for(int i=1;i<=m;i++)
{
int aa,bb;
scanf("%s%d%d",s,&aa,&bb);
if(s[0]=='Q')
{
ans=0;
query(1,1,n,aa,bb);
printf("%lld\n",ans);
}
else
{
long long vv;
scanf("%lld",&vv);
add(1,1,n,aa,bb,vv);
}
}
}