POJ 3468 线段树 区间修改 基础题

A Simple Problem with Integers
Time Limit: 5000MS   Memory Limit: 131072K
Total Submissions: 87262   Accepted: 27084
Case Time Limit: 2000MS

Description

You have N integers, A1A2, ... , 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 A1A2, ... , AN. -1000000000 ≤ Ai ≤ 1000000000.
Each of the next Q lines represents an operation.
"C a b c" means adding c to each of AaAa+1, ... , Ab. -10000 ≤ c ≤ 10000.
"Q a b" means querying the sum of AaAa+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.


题目大意:

给一个序列,C是修改,Q是求值。


恩。。。sum[o]在maintain中的时候要重新赋值,不能直接用书上的sum[o] = 0,而是要之前保存一个sum的值的数组,然后用sum[o] = a[o]才可以。

其他方面好像就没有什么了吧





#include<cstdio> #include<cstring> #include<algorithm> using namespace std; typedef long long ll; const int maxn = 100000 + 5; ll sum[maxn * 4], add[maxn * 4]; ll a[maxn * 4]; ll n, q; ll ans; void buildtree(int o, int l, int r){ if (l == r){ scanf("%I64d", &sum[o]); a[o] = sum[o]; return ; } int mid = l + (r - l) / 2; buildtree(o << 1, l, mid); buildtree(o << 1 | 1, mid + 1, r); sum[o] = sum[o << 1] + sum[o << 1 | 1]; a[o] = sum[o]; } void init(){ memset(sum, 0, sizeof(sum)); memset(add, 0, sizeof(add)); memset(a, 0, sizeof(a)); buildtree(1, 1, n); } void query(int o, int ql, int qr, int l, int r, ll plu){ if (ql <= l && qr >= r){ ans += sum[o] + plu * (r - l + 1); } else { int mid = l + (r - l) / 2; if (mid >= ql){ query(o << 1, ql, qr, l, mid, plu + add[o]); } if(mid < qr){ query(o << 1 | 1, ql, qr, mid + 1, r, plu + add[o]); } } } void maintain(int o, int l, int r){ sum[o] = a[o]; if (l < r){ sum[o] = sum[o << 1] + sum[o << 1 | 1]; } sum[o] += add[o] * (r - l + 1); return ; } void update(int o, int ql, int qr, ll plu, int l, int r){ if (ql <= l && qr >= r){ add[o] += plu; } else { int mid = l + (r - l) / 2; if (mid >= ql){ update(o << 1, ql, qr, plu, l, mid); } if (mid < qr){ update(o << 1 | 1, ql, qr, plu, mid + 1, r); } } maintain(o, l, r); } void solve(){ while (q--){ char ch[2]; scanf("%s", ch); if (ch[0] == 'Q'){ ans = 0; int l, r; scanf("%d%d", &l, &r); query(1, l, r, 1, n, 0); printf("%I64d\n", ans); } else { int l, r; ll plu; scanf("%d%d%I64d", &l, &r, &plu); update(1, l, r, plu, 1, n); } } } int main(){ while (scanf("%I64d%I64d", &n, &q) == 2){ init(); solve(); } return 0; } </algorithm></cstring></cstdio>

你可能感兴趣的:(POJ 3468 线段树 区间修改 基础题)