树状数组

单点修改,区间查询

#include<bits/stdc++.h>
#define ri register int
#define ll long long
#define fast ios::sync_with_stdio(0), cin.tie(0), cout.tie(0)
using namespace std;
#define lb(x) x&(-x)
#define maxn 500005
const inline int read(){
    int k = 0, f = 1; char c = getchar();
    for(;!isdigit(c); c = getchar())
        if(c == '-') f = -1;
    for(;isdigit(c); c = getchar())
        k = k * 10 + c - '0';
    return k * f;
}
int z[maxn], n, m;
inline void insert(int x, int y){
    for(; x <= n; x += lb(x))
        z[x] += y;
}
inline int query(int x){
    int ans = 0;
    for(; x; x -= lb(x))
        ans += z[x];
    return ans;
}
int main(){
    n = read(), m = read();
    for(ri i = 1; i <= n; ++i){
        ri x;
        x = read();
        insert(i, x);
    }
    for(ri i = 1; i <= m; ++i){
        ri s, l, r;
        s = read(), l = read(), r = read();
        if(s == 1)
            insert(l, r);//单点修改 
        else
            printf("%d\n", query(r) - query(l - 1));//区间查询 
    }
    return 0;
}

 

区间修改,单点查询

#include<bits/stdc++.h>
#define ri register int
#define ll long long
#define fast ios::sync_with_stdio(0), cin.tie(0), cout.tie(0)
using namespace std;
#define lb(x) x&(-x)
#define maxn 500005
const inline int read(){
    int k = 0, f = 1; char c = getchar();
    for(;!isdigit(c); c = getchar())
        if(c == '-') f = -1;
    for(;isdigit(c); c = getchar())
        k = k * 10 + c - '0';
    return k * f;
}
int n, m, c[maxn], last = 0;
void add(int x, int y){
    for(; x <= n; x += lb(x))
        c[x] += y;
} 
ll query(int x){
    ll ans = 0;
    for(; x; x -= lb(x))
        ans += c[x];
    return ans;
}
int main(){
    n = read(), m = read();
    for(ri i = 1; i <= n; ++i){
        ri x;
        x = read();
        add(i, x - last);
        last = x;//last 记录上一个数的值,进行差分 
    }
    for(ri i = 1; i <= m; ++i){
        ri q;
        q = read();
        if(q == 1){
            int x, y, k;
            x = read(), y = read(), k = read();
            add(x, k);//(x, n)+k
            add(y + 1, -k);//(y + 1, n)-k;
        }
        else{
            int x;
            x = read();
            printf("%lld\n", query(x));
        }
    }
    return 0;
}

 https://www.cnblogs.com/xenny/p/9739600.html

posted @ 2020-03-20 20:52  kojoker  阅读(132)  评论(0)    收藏  举报