Time Limit: 5000MS | Memory Limit: 131072K | |
Total Submissions: 151063 | Accepted: 46846 | |
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
The sums may exceed the range of 32-bit integers.
Source
POJ Monthly--2007.11.25, Yang Yi
大致题意:
给出了一个序列,你需要处理如下两种询问。
"C a b c"表示给[a, b]区间中的值全部增加c (-10000 ≤ c ≤ 10000)。
"Q a b" 询问[a, b]区间中所有值的和。
解题思路:裸的线段树区间更新
#include <cstdio>
#include <iostream>
#include <cstring>
#include <cmath>
#include <algorithm>
#define mid ((l + r) >> 1)
#define lson rt << 1
#define rson rt << 1 | 1
#define met(a, b) memset(a, b, sizefo(a))
typedef long long ll;
const int INF = 0x3f3f3f3f;
const int MAXN = 1e5 + 10;
ll st[MAXN << 2], cover[MAXN << 2];
using namespace std;
void PushUp(int rt)//向上更新
{
st[rt] = st[lson] + st[rson];
return ;
}
void PushDown(int rt, int len)//向下更新
{
if (cover[rt])
{
cover[lson] += cover[rt];
cover[rson] += cover[rt];
st[lson] += cover[rt] * (len - (len >> 1));
st[rson] += cover[rt] * (len >> 1);
cover[rt] = 0;
}
return ;
}
void Built(int l, int r, int rt)//建树
{
cover[rt] = 0;
if (l == r)
{ scanf("%lld", &st[rt]); return ; }
Built(l, mid, lson);
Built(mid + 1, r, rson);
PushUp(rt);
return ;
}
ll Query(int L, int R, int l, int r, int rt)//查询
{
if (L <= l && r <= R)
return st[rt];
PushDown(rt, r - l + 1);
ll ret = 0;
if (L <= mid)
ret += Query(L, R, l, mid, lson);
if (mid < R)
ret += Query(L, R, mid + 1, r, rson);
return ret;
}
void Update(int L, int R, int w, int l, int r, int rt)//更新区间
{
if (L <= l && r <= R)
{
cover[rt] += w;
st[rt] += (r - l + 1) * (ll)w;
return ;
}
PushDown(rt, r - l + 1);
int m = mid;
if (L <= m)
Update(L, R, w, l, mid, lson);
if (m < R)
Update(L, R, w, mid + 1, r, rson);
PushUp(rt);
return ;
}
int main()
{
int n, m;
while (~scanf("%d %d", &n, &m))
{
Built(1, n, 1);
while (m--)
{
char c;
scanf(" %c", &c);
if (c == 'Q')
{
int l, r;
scanf("%d %d", &l ,&r);
printf("%lld\n", Query(l, r, 1, n, 1));
}
else
{
int l, r, w;
scanf("%d %d %d", &l, &r, &w);
Update(l, r, w, 1, n, 1);
}
}
}
return 0;
}