树状数组

单点修改,区间查询

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cmath>
#define ll long long
using namespace std;
const int MAXN = 500005;
ll init() {
    ll rv = 0, fh = 1;
    char c = getchar();
    while(c < '0' || c > '9') {
        if(c == '-') fh = -1;
        c = getchar();
    }
    while(c >= '0' && c <= '9') {
        rv = (rv<<1) + (rv<<3) + c - '0';
        c = getchar();
    }
    return fh * rv;
}
int n, m, c[MAXN];
ll lowbit(const ll & x){
    return x & -x;
}
ll query(ll x) {
    ll ans = 0;
    for( ; x; x -= lowbit(x)) ans += c[x];
    return ans;
}
void add(ll x, ll y) {
    for( ; x <= n; x += lowbit(x)) c[x] += y;
}
int main() {
    n = init(); m = init();
    for(int i = 1; i <= n; i++) {
        ll a = init();
        add(i, a);
    }
    for(int i = 1; i <= m; i++) {
        ll t = init(), a = init(), b = init();
        if(t == 1ll) add(a, b) ;
        else {
            printf("%lld\n", query(b) - query(a -1));
        }
    }
    return 0;
}

区间修改,单点查询(差分)

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cmath>
#define ll long long
using namespace std;
const int MAXN = 500005;
ll init() {
    ll rv = 0, fh = 1;
    char c = getchar();
    while(c < '0' || c > '9') {
        if(c == '-') fh = -1;
        c = getchar();
    }
    while(c >= '0' && c <= '9') {
        rv = (rv<<1) + (rv<<3) + c - '0';
        c = getchar();
    }
    return fh * rv;
}
ll n, m, c[MAXN];
ll lowbit(const ll &x) {
    return x & -x;
}
ll query(ll x) {
    ll ans = 0;
    for( ; x; x -= lowbit(x)) ans += c[x];
    return ans;
}
void add(ll x, ll y) {
    for( ; x <= n; x += lowbit(x)) c[x] += y;
}
int main() {
    n = init(); m = init();
    for(int i = 1; i <= n; i++) {
        ll t = init();
        add(i, t); add(i + 1, -t);
    }
    for(int i = 1; i <= m; i++) {
        ll t = init();
        if(t == 1){
            ll a = init(), b = init(), k = init();
            add(a, k); add(b + 1, -k);
        }else {
            ll x = init();
            printf("%lld\n", query(x));
        }
    }
    return 0;
}

转载于:https://www.cnblogs.com/Mr-WolframsMgcBox/p/8597387.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值