题目链接:
http://poj.org/problem?id=3468
题解 :
线段树区间更新模版题。
代码:
#include <string>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
#define met(a,b) memset(a,b,sizeof(a))
#define inf 0x3f3f3f3f
#define lchild rt<<1 ,l, m
#define rchild rt<<1|1 ,m+1, r
typedef long long ll;
const ll maxn = 1e5+10;
ll tree[maxn<<2];
ll lazy[maxn<<2];
void push_up(ll rt)
{
tree[rt]=tree[rt << 1]+tree[rt<<1|1];
}
void push_down(ll rt, ll len)
{
tree[rt << 1] += lazy[rt] * (len - (len >> 1));
lazy[rt << 1] += lazy[rt];
tree[rt << 1 | 1] += lazy[rt] * (len >> 1);
lazy[rt << 1 | 1] += lazy[rt];
lazy[rt] = 0;
}
void build(ll rt,ll l,ll r)
{
lazy[rt]=0;
if(l==r)
{
scanf("%lld",&tree[rt]);
return;
}
ll m=(l+r)>>1;
build(lchild);
build(rchild);
push_up(rt);
}
void update(ll L, ll R, ll delta, ll rt, ll l, ll r )
{
if (L <= l && r <= R) {
tree[rt] += delta * (r - l + 1);
lazy[rt] += delta;
return;
}
if (lazy[rt]) push_down(rt, r - l + 1);
ll m = (l + r) >> 1;
if (L <= m) update(L, R, delta, lchild);
if (R > m) update(L, R, delta, rchild);
push_up(rt);
}
ll query(ll L, ll R, ll rt, ll l, ll r)
{
if (L <= l && r <= R) return tree[rt];
if (lazy[rt]) push_down(rt, r - l + 1);
ll m = (l + r) >> 1, ret = 0;
if (L <= m) ret += query(L, R, lchild);
if (R > m) ret += query(L, R, rchild);
return ret;
}
int main()
{
ll n,q;
while(scanf("%lld%lld",&n,&q)!=EOF)
{
build(1,1,n);
while(q--)
{
char s[10];
scanf("%s",s);
if(s[0]=='C')
{
ll a,b,c;
scanf("%lld%lld%lld",&a,&b,&c);
update(a,b,c,1,1,n);
}
if(s[0]=='Q')
{
ll a,b;
scanf("%lld%lld",&a,&b);
printf("%lld\n",query(a,b,1,1,n));
}
}
}
}
1487

被折叠的 条评论
为什么被折叠?



