zoukankan      html  css  js  c++  java
  • 树状数组

    #include <iostream>
    #include <cstdio>
    
    using namespace std;
    
    const int maxn=5e5+10;
    
    long long a[maxn],c[maxn];
    
    inline int lowbit(int x)
    {
        return x&(-x);
    }
    
    void build(int n)
    {
        for(int i=1;i<=n;i++)
        {
            for(int j=i;j<=n;j+=lowbit(j))
                c[j]+=a[i];
        }
        return ;
    }
    
    void update(int x,int k,int n)
    {
        for(;x<=n;x+=lowbit(x))c[x]+=k;
    }
    
    long long query(int x)
    {
        long long ans=0;
        while(x)
        {
            ans+=c[x];
            x-=lowbit(x);
        }
        return ans;
    }
    
    int main()
    {
        int n,m;
        scanf("%d %d",&n,&m);
        for(int i=1;i<=n;i++)
        {
            scanf("%lld",&a[i]);
        }
        build(n);
        int op,x,y;
        while(m--)
        {
            scanf("%d %d %d",&op,&x,&y);
            if(op==1)
            {
                update(x,y,n);
            }
            else
            {
                if(x>y)
                    swap(x,y);
                printf("%lld
    ",query(y)-query(x-1));
            }
        }
        return 0;
    }
    单点修改
    #include <iostream>
    #include <cstdio>
    
    using namespace std;
    
    const int maxn=5e5+10;
    
    long long a[maxn],c[maxn],b[maxn];
    
    inline int lowbit(int x)
    {
        return x&(-x);
    }
    
    void build(int n)
    {
        for(int i=1;i<=n;i++)
        {
            for(int j=i;j<=n;j+=lowbit(j))
                c[j]+=a[i];
        }
        return ;
    }
    
    void update(int x,int k,int n)
    {
        for(;x<=n;x+=lowbit(x))c[x]+=k;
    }
    
    long long query(int x)
    {
        long long ans=0;
        while(x)
        {
            ans+=c[x];
            x-=lowbit(x);
        }
        return ans;
    }
    
    int main()
    {
        int n,m;
        scanf("%d %d",&n,&m);
        for(int i=1;i<=n;i++)
        {
            scanf("%lld",&b[i]);
            a[i]=b[i]-b[i-1];
        }
        build(n);
        int op,x,y,k;
        while(m--)
        {
            scanf("%d %d",&op,&x);
            if(op==1)
            {
                scanf("%d %d",&y,&k);
                update(x,k,n);
                update(y+1,-k,n);
            }
            else
            {
                printf("%lld
    ",query(x));
            }
        }
        return 0;
    }
    区间修改,单点查询
  • 相关阅读:
    拉普拉斯矩阵
    正定矩阵 和 半正定矩阵
    Random Walk
    论文解读(DGI)《DEEP GRAPH INFOMAX》
    python安装easyinstall/pip出错
    pip国内源设置
    在Jupyter Notebook添加代码自动补全功能
    [BUUCTF]PWN——bjdctf_2020_babystack2
    [BUUCTF]REVERSE——[BJDCTF 2nd]8086
    [BUUCTF]PWN——jarvisoj_tell_me_something
  • 原文地址:https://www.cnblogs.com/wyhbadly/p/11552440.html
Copyright © 2011-2022 走看看