A Simple Problem with Integers (線段樹應用型別三)【區間增加 區間查詢】【模板基礎題】
阿新 • • 發佈:2019-01-11
題目連結:http://poj.org/problem?id=3468
參考部落格:https://blog.csdn.net/u013480600/article/details/22202711
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
"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
題意:增加給定區間的值,查詢區間和。(注意資料大小)
//POJ 3468 區間add,區間查詢
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
//每當有add加到i節點上,直接更新i節點的sum.
//也就是說如果要查詢區間[1,n]的sum值,直接sum[1]即可,不用再去考慮1的addv[1]值.
const int MAXN=100000+100;
#define LL long long
#define lson i*2,l,m
#define rson i*2+1,m+1,r
LL sum[MAXN*4];
LL addv[MAXN*4];
void PushDown(int i,int num)
{
if(addv[i])
{
sum[i*2] +=addv[i]*(num-(num/2));
sum[i*2+1] +=addv[i]*(num/2);
addv[i*2] +=addv[i];
addv[i*2+1]+=addv[i];
addv[i]=0;
}
}
void PushUp(int i)
{
sum[i]=sum[i*2]+sum[i*2+1];
}
void build(int i,int l,int r)
{
addv[i]=0;
if(l==r)
{
scanf("%lld",&sum[i]);
return ;
}
int m=(l+r)/2;
build(lson);
build(rson);
PushUp(i);
}
void update(int ql,int qr,int add,int i,int l,int r)
{
if(ql<=l&&r<=qr)
{
addv[i]+=add;
sum[i] += (LL)add*(r-l+1);
return ;
}
PushDown(i,r-l+1);
int m=(l+r)/2;
if(ql<=m) update(ql,qr,add,lson);
if(m<qr) update(ql,qr,add,rson);
PushUp(i);
}
LL query(int ql,int qr,int i,int l,int r)
{
if(ql<=l&&r<=qr)
{
return sum[i];
}
PushDown(i,r-l+1);
int m=(l+r)/2;
LL res=0;
if(ql<=m) res+=query(ql,qr,lson);
if(m<qr) res+=query(ql,qr,rson);
return res;
}
int main()
{
int n,q;
scanf("%d%d",&n,&q);
build(1,1,n);
char s1[5];
for(int i=1;i<=q;i++)
{
scanf("%s",s1);
if(s1[0]=='Q')
{
int a,b;
scanf("%d%d",&a,&b);
printf("%lld\n",query(a,b,1,1,n));
}
else
{
int a,b,c;
scanf("%d%d%d",&a,&b,&c);
update(a,b,c,1,1,n);
}
}
return 0;
}