您的位置:首页 > 其它

[POJ3468]A Simple Problem with Integers

2015-08-30 22:14 260 查看
题目链接:http://poj.org/problem?id=3468

线段树区间更新查询的样题,注意数据范围。连要更新的数据也必须是long long。

#include <algorithm>
#include <iostream>
#include <iomanip>
#include <cstring>
#include <climits>
#include <complex>
#include <cassert>
#include <cstdio>
#include <bitset>
#include <vector>
#include <deque>
#include <queue>
#include <stack>
#include <ctime>
#include <set>
#include <map>
#include <cmath>
using namespace std;

typedef long long LL;
#define lrt rt << 1
#define rrt rt << 1 | 1
const int maxn = 100100;
LL sum[maxn<<2], add[maxn<<2];
int n, q;
char cmd[2];

void pushUP(int rt) {
sum[rt] = sum[lrt] + sum[rrt];
}

void pushDOWN(int rt, int len) {
if(add[rt]) {
sum[lrt] += (len - len / 2) * add[rt];
sum[rrt] += len / 2 * add[rt];
add[lrt] += add[rt];
add[rrt] += add[rt];
add[rt] = 0;
}
}

void build(int l, int r, int rt) {
add[rt] = 0;
if(l == r) {
scanf("%I64d", &sum[rt]);
return;
}
int mid = (l + r) >> 1;
build(l, mid, lrt);
build(mid+1, r, rrt);
pushUP(rt);
}

void update(int L, int R, LL c, int l, int r, int rt) {
if(L <= l && r <= R) {
add[rt] += c;
sum[rt] += (LL)c * (r - l + 1);
return;
}
pushDOWN(rt, r-l+1);
int mid = (l + r) >> 1;
if(L <= mid) update(L, R, c, l, mid, lrt);
if(mid < R) update(L, R, c, mid+1, r, rrt);
pushUP(rt);
}

LL query(int L, int R, int l, int r, int rt) {
if(L <= l && r <= R) return sum[rt];
pushDOWN(rt, r-l+1);
int mid = (l + r) >> 1;
LL ret = 0;
if(L <= mid) ret += query(L, R, l, mid, lrt);
if(mid < R) ret += query(L, R, mid+1, r, rrt);
return ret;
}

int main() {
// freopen("in", "r", stdin);
int l, r, c;
while(~scanf("%d%d",&n,&q)) {
build(1, n, 1);
while(q--) {
scanf("%s", cmd);
if(cmd[0] == 'Q') {
scanf("%d%d",&l,&r);
printf("%I64d\n", query(l,r,1,n,1));
}
else {
scanf("%d%d%d",&l,&r,&c);
update(l,r,LL(c),1,n,1);
}
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: