线段树 (区间更新,区间查询) poj http://poj.org/problem?id=3468

题目链接

#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstdlib>
#include<cstring>
#include<string> using namespace std;
const int N = ;
typedef long long int LL;
LL sum[N << ];
LL add[N << ];
struct node
{
int l, r;
int mid()
{
return (l + r) >> ;
}
}tree[N << ];
void PushUp(int rt)
{
sum[rt] = sum[rt << ] + sum[rt << | ];
}
void PushDown(int rt, int m)
{
if (add[rt]) {
add[rt << ] += add[rt];
add[rt << | ] += add[rt];
sum[rt << ] += add[rt] * (m - (m >> ));
sum[rt << | ] += add[rt] * (m >> );
add[rt] = ;//更新后要还原,因为递归可能会多次用到这个
}
} void build(int l,int r,int rt)
{
tree[rt].l = l;
tree[rt].r = r;
add[rt] = ;
if (l == r) {
scanf("%lld", &sum[rt]);
return;
}
int m = tree[rt].mid();
build(l, m, rt << );
build(m + , r, rt << | );
PushUp(rt);
} void updata(int c, int l, int r, int rt)
{
if (tree[rt].l == l && r == tree[rt].r) {
add[rt] += c;
sum[rt] += (LL)(r - l + )*c;
return;//这里没有进行子区间更新,用到lazy标记
}
if (tree[rt].l == tree[rt].r) return;
PushDown(rt, tree[rt].r - tree[rt].l + );
int m = tree[rt].mid();
if (r <= m) updata(c,l, r, rt << );
else if (l > m) updata(c,l, r, rt << | );
else {
updata(c, l, m, rt << );
updata(c, m + , r, rt << | );
}
PushUp(rt); } LL query(int l, int r, int rt)
{
if (l == tree[rt].l&&r == tree[rt].r) {
return sum[rt];
}
PushDown(rt, tree[rt].r - tree[rt].l + );//标记的特点,用时才进行更新
int m = tree[rt].mid();
LL res = ;
if (r <= m) res += query(l, r, rt << );
else if (l > m) res += query(l, r, rt << | );
else {
res += query(l, m, rt << );
res += query(m + , r, rt << | );
}
return res;
}
int main()
{
int n, m;
while (scanf("%d %d", &n, &m) == ) {
memset(sum, , sizeof(sum));
memset(add, , sizeof(add));
build(, n, );
while (m--) {
char ch[];
scanf("%s", ch);
if (ch[] == 'Q') {
int a, b;
scanf("%d %d", &a, &b);
printf("%lld\n", query(a, b, ));
}
else {
int a, b, c;
scanf("%d %d %d", &a, &b, &c);
updata(c, a, b, );
}
}
} return ;
}
上一篇:http://poj.org/problem?id=2253


下一篇:poj 1679 http://poj.org/problem?id=1679