A Simple Problem with Integers POJ - 3468 (线段树区间增减,区间查询模板)

xiaoxiao2021-02-28  106

A Simple Problem with Integers Time Limit: 5000MS Memory Limit: 131072KTotal Submissions: 117870 Accepted: 36662Case 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

The sums may exceed the range of 32-bit integers.

Source

POJ Monthly--2007.11.25, Yang Yi

题目大意:在一个数组中询问一个区间和或者对于一个区间同时增加或者减少

#include <cstdio> #include <cstring> #include <iostream> #include <algorithm> #include <vector> #include <queue> #include <set> #include <map> #include <string> #include <cmath> #include <cstdlib> #include <ctime> using namespace std; typedef long long LL; const int MAXN = 1e5 + 5; struct tree { LL flag,sum; }a[MAXN * 4 + 5]; int n,m; void pushup(int deep) { a[deep].sum = a[deep * 2].sum + a[deep * 2 + 1].sum; } void build(int l ,int r,int deep) { a[deep].flag = 0; if(l == r) { scanf("%lld",&a[deep].sum); return; } int mid = (l + r) / 2; build(l,mid,deep * 2); build(mid+1,r,deep * 2 + 1); pushup(deep); } void pushdown(int deep,int longs) { if(a[deep].flag) { a[deep * 2].flag += a[deep].flag; a[deep * 2 +1].flag += a[deep].flag; a[deep * 2].sum += a[deep].flag * (longs - longs / 2); a[deep * 2 + 1].sum += a[deep].flag * (longs / 2); a[deep].flag = 0; } } void update(int L , int R ,int k , int l , int r, int deep) { if( L <= l && r <= R) { a[deep].flag += k; a[deep].sum += (LL) k * (r - l + 1); return; } pushdown(deep,r-l+1); int mid = (l + r) / 2; if(L <= mid) update(L,R,k,l,mid,deep * 2); if(mid < R) update(L,R,k,mid+1,r,deep * 2 + 1); pushup(deep); } LL query(int L,int R,int l,int r,int deep) { if( L <= l && r <= R) return a[deep].sum; pushdown(deep,r-l+1); LL sum=0; int mid = (l + r) / 2; if(L <= mid) sum += query(L,R,l,mid,deep * 2); if(mid < R) sum += query(L,R,mid+1,r,deep * 2 + 1); return sum; } int main() { char s[2]; LL k; int x,y; scanf("%d%d",&n,&m); build(1 , n , 1); while(m--) { scanf("%s",&s); if(s[0] == 'Q') { scanf("%d%d",&x,&y); printf("%lld\n",query(x , y , 1 , n , 1)); } else { scanf("%d%d%d",&x,&y,&k); update(x,y,k,1,n,1); } } return 0; }

转载请注明原文地址: https://www.6miu.com/read-51152.html

最新回复(0)