题目链接:http://poj.org/problem?id=3468
题目:
A Simple Problem with Integers
Time Limit: 5000MS Memory Limit: 131072K
Total Submissions: 169094 Accepted: 52129
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
目的:主要是练习一下线段树动态开点的操作,这道题目其实不用动态开点;
动态开点的思路:
原来我们的静态开点就是 s * 2, s * 2 + 1;这里的动态开点则是直接使用一个全局变量作为某种意义上的地址,就像数组模拟邻接表一样。但是当去判断往哪个方向递归的时候,还是需要用到 mid = (l + r) / 2;其最大的好处就在于节约了地址空间;(以前不太懂,为后面些主席树做准备)
AC代码:
#include <iostream>
#include <cstdio>
#include <cmath>
using namespace std;
typedef long long LL;
const int maxn = 1e5 + 5;
struct SegmentTree {
LL sum, lazy;
int lc, rc;
}t[maxn * 4];
int n, m, cnt, root;
inline int build(void) {
++ cnt;
t[cnt].lc = t[cnt].rc = t[cnt].sum = 0;
return cnt;
}
inline void insert(int &root, int l, int r, int ll, int rr, LL x) {
if(!root) root = build();
if(l == r) { t[root].sum += x; return; }
LL b = min(r, rr) - max(l, ll) + 1;
t[root].sum += b * x;
if(ll <= l && rr >= r) {
t[root].lazy += x;
return;
}
int mid = (l + r) >> 1;
if(ll <= mid) insert(t[root].lc, l, mid, ll, rr, x);
if(mid < rr) insert(t[root].rc, mid + 1, r, ll, rr, x);
}
inline LL query(int root, int l, int r, int ll, int rr) {
if(ll <= l && rr >= r) return t[root].sum;
int mid = (l + r) >> 1;
if(t[root].lazy) {
if(!t[root].lc) t[root].lc = build();
t[t[root].lc].lazy += t[root].lazy;
t[t[root].lc].sum += t[root].lazy * (mid - l + 1);
if(!t[root].rc) t[root].rc = build();
t[t[root].rc].lazy += t[root].lazy;
t[t[root].rc].sum += t[root].lazy * (r - mid);
t[root].lazy = 0;
}
LL ans = 0;
if(ll <= mid) ans += query(t[root].lc, l, mid, ll, rr);
if(mid < rr) ans += query(t[root].rc, mid + 1, r, ll, rr);
return ans;
}
int main(void) {
// freopen("in.txt", "r", stdin);
scanf("%d%d", &n, &m);
root = build();
for(int i = 1; i <= n; i ++) {
LL tmp; scanf("%lld", &tmp);
insert(root, 1, n, i, i, tmp);
}
for(int i = 1; i <= m; i ++) {
char op[5];
scanf("%s", op);
if(op[0] == 'Q') {
int l, r; scanf("%d%d", &l, &r);
printf("%lld\n", query(root, 1, n, l, r));
} else {
int l, r, c; scanf("%d%d%d", &l, &r, &c);
insert(root, 1, n, l, r, c);
}
}
// fclose(stdin);
return 0;
}
总结:
这道题目,我写的时候wa了2发,其原因在于第一次开点的时候没有特殊判断,导致了我的叶子节点的延迟标记用了2次,导致错误。