A Simple Problem with Integers
| Time Limit: 5000MS | Memory Limit: 131072K | |
| Total Submissions: 89835 | Accepted: 27972 | |
| 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.
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
题目大意:
就是给你一个数列,让你进行区间操作,c表示把a到b的数都加上c;q表示输出a到b的所有的数的总和。
#include<iostream>
#include<cstdio>
using namespace std;
const long long maxn=233333;
int xl[maxn];
struct love{
int l,r;
long long sum,add;
}liuwen[maxn*4];
void build(int p,int l,int r)
{
liuwen[p].l=l;
liuwen[p].r=r;
if(l==r)
{
liuwen[p].sum=xl[l];
return ;
}
int mid=(l+r)/2;
build(p*2,l,mid);
build(p*2+1,mid+1,r);
liuwen[p].sum=liuwen[p*2].sum+liuwen[p*2+1].sum;
}
void spread(int p)
{
if(liuwen[p].add){
liuwen[p*2].sum+=(liuwen[p*2].r-liuwen[p*2].l+1)*(long long)liuwen[p].add;
liuwen[p*2+1].sum+=(liuwen[p*2+1].r-liuwen[p*2+1].l+1)*(long long)liuwen[p].add;
liuwen[p*2].add+=liuwen[p].add;
liuwen[p*2+1].add+=liuwen[p].add;
liuwen[p].add=0;
}
}
void change(int p,int l,int r,long long x)
{
if(l<=liuwen[p].l&&liuwen[p].r<=r)
{
liuwen[p].sum+=(long long)(liuwen[p].r-liuwen[p].l+1)*x;
liuwen[p].add+=x;
return ;
}
spread(p);
int mid=(liuwen[p].l+liuwen[p].r)/2;
if(l<=mid)
change(p*2,l,r,x);
if(mid< r)
change(p*2+1,l,r,x);
liuwen[p].sum=liuwen[p*2].sum+liuwen[p*2+1].sum;
}
long long ask(int p,int l,int r)
{
if(l<=liuwen[p].l&&liuwen[p].r<=r)
{
return liuwen[p].sum;
}
spread(p);
long long ans=0;
int mid=(liuwen[p].l+liuwen[p].r)/2;
if(l<=mid) ans+=ask(p*2,l,r);
if(mid<r) ans+=ask(p*2+1,l,r);
return ans;
}
int main()
{
long long n,q;
cin>>n>>q;
for(int i=1;i<=n;i++)
{
scanf("%d",&xl[i]);
}
build(1,1,n);
for(int i=1;i<=q;i++){
char ss = getchar();
while(ss != 'Q' && ss != 'C')
ss = getchar();
if(ss=='Q')
{
int a,b;
scanf("%d%d",&a,&b);
printf("%lld\n",ask(1,a,b));
}
if(ss=='C')
{
int a,b;
long long c;
scanf("%d%d%lld",&a,&b,&c);
change(1,a,b,c);
}
}
return 0;
}