POJ-3468 ---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 4Sample Output
4 55 9 15Hint
题解:这是一道线段树区间修改的问题,看代码就会明白的。。。。(这道题的代码建议好好看看,可以作为模版)
AC代码为:
#include<cstdio>
#include<cstring>
#define maxl 200001
long long n,q;
long long a[maxl];
struct node {long long l,r,sum,tag;};
node tree[maxl<<2];
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()
{
scanf("%lld%lld",&n,&q);
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 ch;
for(long long i=1;i<=q;i++)
{
getchar();
scanf("%c",&ch);
if(ch=='C')
{
scanf("%lld%lld%lld",&l,&r,&x);
add(1,l,r,x);
}
else if(ch=='Q')
{
scanf("%lld%lld",&l,&r);
printf("%lld\n",query(1,l,r));
}
}
}
int main()
{
prework();
mainwork();
return 0;
}