2.A Simple Problem with Integers
2019-07-25 本文已影响0人
miaozasnone
2.A Simple Problem with Integers
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.
输入
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.
输出
You need to answer all Q commands in order. One answer in a line.
样例输入
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
样例输出
4
55
9
15
ac代码
#include<cstdio>
#include<cstring>
#define maxl 1000000
long long n,q;
long long a[maxl];
struct node {long long l,r,sum,tag;};
node tree[maxl<<2];
node zerot={0,0,0,0};
void build(long long k,long long l,long long r)
{
tree[k].l=l;tree[k].r=r;
if(l==r)
{
tree[k].sum=a[l];
return;
}
long long mid=(tree[k].l+tree[k].r)>>1;
build(k<<1,l,mid);
build(k<<1|1,mid+1,r);
tree[k].sum=tree[k<<1].sum+tree[k<<1|1].sum;
}
void prework()
{
for(long long i=1;i<=n;i++)
scanf("%lld",&a[i]);
build(1,1,n);
}
void change(long long k)
{
if(tree[k].l==tree[k].r)
tree[k].sum+=tree[k].tag;
else
{
tree[k].sum+=(tree[k].r-tree[k].l+1)*tree[k].tag;
tree[k<<1].tag+=tree[k].tag;
tree[k<<1|1].tag+=tree[k].tag;
}
tree[k].tag=0;
}
void add(long long k,long long l,long long r,long long x)
{
if(tree[k].tag)
change(k);
if(tree[k].l==l && tree[k].r==r)
{
tree[k].tag+=x;
return;
}
tree[k].sum+=(r-l+1)*x;
long long mid=(tree[k].l+tree[k].r)>>1;
if(r<=mid)
add(k<<1,l,r,x);
else
if(l>mid)
add(k<<1|1,l,r,x);
else
add(k<<1,l,mid,x),add(k<<1|1,mid+1,r,x);
}
long long query(long long k,long long l,long long r)
{
if(tree[k].tag)
change(k);
long long sum,mid=(tree[k].l+tree[k].r)>>1;
if(tree[k].l==l && tree[k].r==r)
return tree[k].sum;
if(r<=mid)
return query(k<<1,l,r);
else
if(l>mid)
return query(k<<1|1,l,r);
else
return query(k<<1,l,mid)+query(k<<1|1,mid+1,r);
}
void mainwork()
{
long long l,r,x;
char c[2];
//printf("%lld\n",q);
for(long long i=1;i<=q;i++)
{
//getchar();
scanf("%s",c);
//getchar();
//printf("%c",c);
if(c[0]=='C')
{
//printf("1\n");
scanf("%lld%lld%lld",&l,&r,&x);
add(1,l,r,x);
}
if(c[0]=='Q')
{
scanf("%lld%lld",&l,&r);
printf("%lld\n",query(1,l,r));
}
}
}
int main()
{
while(scanf("%lld%lld",&n,&q)!=EOF){
memset(tree,0,sizeof(tree));
prework();
mainwork();
}
return 0;
}