首页 > 代码库 > Problem B SPOJ DCEPC11I
Problem B SPOJ DCEPC11I
Description
Vaibhav Sir and Saikat Sir, after completing their graduation, got a job together at a store.
Their boss at the store was Sidharth Sir, who was very strict and did not want anyone to have fun at the job. He gave Vaibhav and Saikat sir a very boring job of stacking columns of boxes in a row of size N.
To make it a little interesting, both of them decided that whenever they need to add more boxes, they will choose st and en, such that 1<=st<=en<=N, and place 1 box in column st, 2 boxes in column st+1, … and (en-st+1) boxes in column en.
When Sidharth sir saw this, he decided to have some fun of his own, and asked them to count the number of boxes in all columns from st to en, and tell him the result. Now Vaibhav and Saikat sir have come to you for help to answer the queries of their boss, as they do not want to lose their jobs.
Input
The first line contains N, the number of columns and Q, the number of queries.
The next Q lines can be of the following form –
1) 0 st en, meaning Vaibhav and Saikat sir add boxes to the columns from st to en as described above.
2) 1 st en, meaning Sidharth sir asks them to count the number of boxes in all columns from st to en.
Output
For all queries of type 2, output a line containing the answer to the query.
Example
Input: 5 6
0 2 4
1 1 5
0 1 5
0 3 5
1 1 5
1 3 5 Output: 6
27
23
Constraints:
1<=N, Q<=100000
#include <iostream>#include <cstdio>#include <cstring>#include <algorithm>using namespace std;typedef long long LL ;const int maxn = 100005 ;#define Lson o<<1, L, mid#define Rson o<<1|1 , mid+1 , RLL a[maxn<<2] , d[maxn<<2] , sum[maxn<<2] ;void pushup(int o){ sum[o] = sum[o<<1] + sum[o<<1|1] ;}void pushdown(int o , int c1 , int c2) { if(a[o] || d[o]) { LL a1 = a[o] , a2 = a[o] + (LL)d[o] * c1 ; sum[o<<1] += a1*c1 + c1*(c1-1)*d[o]/2 ; sum[o<<1|1] += a2*c2 + c2*(c2-1)*d[o]/2; a[o<<1] += a1 , a[o<<1|1] += a2 ; d[o<<1] += d[o] , d[o<<1|1] += d[o] ; a[o] = d[o] = 0 ; }}int l , r ;void update(int o ,int L ,int R){ if(l<=L && R<=r) { LL a1 = L - l + 1 , c1 = R - L + 1 ; sum[o] += a1*c1 + c1*(c1-1)/2; a[o] += a1 , d[o]++ ; return ; } int mid = (L+R)>>1; pushdown(o, mid-L+1 , R-mid); if(l<=mid) update(Lson) ; if(r>mid) update(Rson) ; pushup(o);}LL query(int o ,int L ,int R) { if(l<=L && R<=r) return sum[o]; int mid = (L+R)>>1 ; pushdown(o , mid-L+1 , R-mid) ; LL ret = 0 ; if(l<=mid) ret += query(Lson) ; if(r> mid) ret += query(Rson) ; return ret;}int main(){ int N , Q; scanf("%d%d", &N ,&Q); while(Q--){ int op ; scanf("%d%d%d", &op, &l ,&r) ; if(op == 0) update(1, 1 , N) ; else printf("%lld\n" , query(1, 1 ,N) ) ; } return 0;}