HDU-1166 单点更新
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <vector>
#include <cmath>
#include <set>
using namespace std;
typedef long long ll;
const int maxn = 50005;
int tree[maxn << 2], a[maxn];
int n;
void build(int rt, int l, int r) {
if (l == r) {
tree[rt] = a[l];
return;
}
int mid = (l + r) >> 1;
build(rt << 1, l, mid);
build(rt << 1 | 1, mid + 1, r);
tree[rt] = tree[rt << 1] + tree[rt << 1 | 1];
}
void update(int rt, int l, int r, int pos, int num) {
if (l == r) {
tree[rt] += num;
return;
}
int mid = (l + r) >> 1;
if (pos <= mid)update(rt << 1, l, mid, pos, num);
else update(rt << 1 | 1, mid + 1, r, pos, num);
tree[rt] = tree[rt << 1] + tree[rt << 1 | 1];
}
int query(int rt, int l, int r, int x, int y) {
if (x <= l && y >= r) return tree[rt];
int mid = (l + r) >> 1;
if (y <= mid)return query(rt << 1, l, mid, x, y);
else if (x > mid)return query(rt << 1 | 1, mid + 1, r, x, y);
return query(rt << 1, l, mid, x, mid) + query(rt << 1 | 1, mid + 1, r, mid + 1, y);
}
int t;
int main() {
ios::sync_with_stdio(false);
int cas = 1;
cin >> t;
while (t--) {
cin >> n;
for (int i = 1; i <= n; i++)
cin >> a[i];
build(1, 1, n);
string op;
cout << "Case " << cas++ << ":" << endl;
while (cin >> op && op[0] != 'E') {
int a, b;
cin >> a >> b;
if (op[0] == 'Q') {
cout << query(1, 1, n, a, b) << endl;
}
else if (op[0] == 'A') {
update(1, 1, n, a, b);
}
else if (op[0] == 'S') {
update(1, 1, n, a, -b);
}
}
}
return 0;
}
POJ-3468 区间更新
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <vector>
#include <cmath>
#include <set>
using namespace std;
typedef long long ll;
const ll maxn=100005;
ll tree[maxn<<2];
ll a[maxn];
ll add[maxn<<2];
ll n,m;
void build(ll rt, ll l, ll r) {
add[rt]=0;
if(l==r) {
tree[rt]=a[l];
return ;
}
ll mid=(l+r)>>1;
build(rt<<1, l, mid);
build(rt<<1|1, mid + 1, r);
tree[rt]=tree[rt<<1]+tree[rt<<1|1];
}
void push_down(ll rt, ll m) {
if(add[rt]) {
add[rt<<1]+=add[rt];
add[rt<<1|1]+=add[rt];
tree[rt<<1]+=add[rt]*(m-(m>>1));
tree[rt<<1|1]+=add[rt]*(m>>1);
add[rt]=0;
}
}
void update(ll rt, ll l, ll r, ll x, ll y, ll num) {
if(x<=l&&y>=r) {
add[rt]+=num;
tree[rt]+=num*(r-l+1);
return ;
}
push_down(rt,r-l+1);
ll mid=(l+r)>>1;
if(y<=mid)update(rt<<1,l,mid,x,y,num);
else if(x>mid)update(rt<<1|1,mid+1,r,x,y,num);
else {
update(rt<<1,l,mid,x,mid,num);
update(rt<<1|1,mid+1,r,mid+1,y,num);
}
tree[rt]=tree[rt<<1]+tree[rt<<1|1];
}
ll query(ll rt,ll l,ll r,ll x,ll y) {
if(x<=l&&y>=r) return tree[rt];
push_down(rt,r-l+1);
ll mid=(l+r)>>1;
if(y<=mid)return query(rt<<1,l,mid,x,y);
else if(x>mid)return query(rt<<1|1,mid+1,r,x,y);
return query(rt<<1,l,mid,x,y)+query(rt<<1|1,mid+1,r,x,y);
}
int main () {
ios::sync_with_stdio(false);
cin>>n>>m;
for(ll i=1;i<=n;i++)
cin>>a[i];
build(1,1,n);
for(ll i=0;i<m;i++) {
char c;
ll d1,d2;
cin>>c>>d1>>d2;
if(c=='Q') cout<<query(1,1,n,d1,d2)<<endl;
else if(c=='C') {
ll d3;
cin>>d3;
update(1,1,n,d1,d2,d3);
}
}
return 0;
}