树状数组BIT

模板1

#include<iostream>
#include<cstdio>
using namespace std;

int n, m, c[500010];

inline int read(){
    int s=0,w=1;
    char ch=getchar();
    while(ch<'0'||ch>'9')   { if(ch=='-')w=-1; ch=getchar(); }
    while(ch>='0'&&ch<='9') { s=s*10+ch-'0';   ch=getchar(); }
    return s*w;
}

void update(int x, int y){ for(; x<=n; x+=x&-x) c[x]+=y; }

int sum(int x){
    int ans=0;
    for(; x; x-=x&-x)   ans+=c[x];
    return ans;
}

int main(){
    n=read(), m=read();
    for(int i=1, t; i<=n; i++)  t=read(), update(i, t);
    for(int i=1, k, x, y; i<=m; i++)
    {
        k=read(), x=read(), y=read();
        if(k==1)    update(x, y);
        else        printf("%d\n", sum(y)-sum(x-1));
    }
    return 0;
}

模板2

#include<iostream>
#include<cstdio>
using namespace std;
int N, M, C[500010], A[500010];
inline int read()
{
    int s=0, w=1;
    char ch=getchar();
    while(ch<'0' || ch>'9'){ if(ch=='-') w=-1; ch=getchar();}
    while(ch>='0'&&ch<='9'){ s=s*10+ch-'0';    ch=getchar();}
    return s*w;
}

void update(int x, int y){ for(; x<=N; x+=x&-x)  C[x]+=y; }
int sum(int x)
{
    int ans=0;
    for(; x; x-=x&-x) ans+=C[x];
    return ans;
}

int main(){
    N=read(), M=read();
    for(int i=1; i<=N; i++)
    {
        int t=read();
        A[i]=t;
        update(i, t-A[i-1]);
    }
    for(int i=1; i<=M; i++)
    {
        int t=read();
        if(t==1)
        {
            int x, y, k;
            x=read(), y=read(), k=read();
            update(x, k);
            update(y+1, -k);
        }else
        {
            int x=read();
            printf("%d\n", sum(x));
        }
    }
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/lfyzoi/p/10573136.html