poj 3468 A Simple Problem with Integers (线段树成段更新)
Time Limit: 5000MS | Memory Limit: 131072K | |
Total Submissions: 77486 | Accepted: 23862 | |
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
Source
题目链接:http://poj.org/problem?id=3468
题目大意:C情况时a-b区间内每一个数字加入c。Q情况时查询区间内值的和。
解题思路:模板线段树成段更新问题。
代码例如以下:
#include <cstdio> #include <cstring> #define inf 1e12 #define ll long long const ll maxn=1000010; ll n,m,a,b,c; ll sum[maxn],nd[maxn]; char s[2]; void build(ll l,ll r,ll root) { ll mid=(l+r)/2; if(l==r) { scanf("%lld",&sum[root]); return; } build(l,mid,root*2); build(mid+1,r,root*2+1); sum[root]=sum[root*2]+sum[root*2+1]; } void pushdown(ll l,ll root) { if(nd[root]!=0) { nd[root*2]+=nd[root]; nd[root*2+1]+=nd[root]; sum[root*2]+=((l-l/2)*nd[root]); sum[root*2+1]+=((l/2)*nd[root]); nd[root]=0; } } ll query(ll l,ll r,ll root) { if(l>=a&&r<=b) return sum[root]; pushdown(r-l+1,root); ll mid=(l+r)/2,ans=0; if(a<=mid) ans+=query(l,mid,root*2); if(b>mid) ans+=query(mid+1,r,root*2+1); return ans; } void update(ll l,ll r,ll root) { if(l>b||r<a) return; ll len=r-l+1; if(l>=a&&r<=b) { nd[root]+=c; sum[root]+=(len*c); return ; } pushdown(len,root); int mid=(l+r)/2; if(a<=mid) update(l,mid,root*2); if(b>mid) update(mid+1,r,root*2+1); sum[root]=sum[root*2]+sum[root*2+1]; } int main(void) { memset(nd,0,sizeof(nd)); scanf("%lld%lld",&n,&m); build(1,n,1); for(ll i=0;i<m;i++) { scanf("%s",s); if(s[0]=='Q') { scanf("%lld%lld",&a,&b); printf("%lld\n",query(1,n,1)); } else { scanf("%lld%lld%lld",&a,&b,&c); update(1,n,1); } } }