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

    树状数组单点修改区间查询

    #include<iostream>
    using namespace std;
    int n,m;
    int tree[2000020];
    int lowbit(int x)
    {
        return x&(-x);
    }
    void update(int x,int v)
    {
        while(x<=n)
        {
            tree[x]+=v;
            x+=lowbit(x);
        }
    }
    int sum(int x)
    {
        int res=0;
        while(x>0)
        {
            res+=tree[x];
            x-=lowbit(x);
        }
        return res;
    }
    int main()
    {
        ios::sync_with_stdio(false);
        int k;
        std::cin>>n>>m;
        for(int i=1;i<=n;i++)
        {
            std::cin>>k;
            update(i,k);
        }
        int a,b,c;
        while(m--)
        {
            std::cin>>a>>b>>c;
            if(a==1)
            {
                update(b,c);
            }
            else
            {
                cout<<(sum(c)-sum(b-1))<<endl;
            }
        }
        cin.tie(0);
        return 0;
    }

    树状数组区间修改单点查询

    #include<iostream>
    using namespace std;
    typedef long long ll;
    int n,m;
    ll tree[500010],nm[500010];
    ll lowbit(ll x)
    {
        return x&(-x);
    }
    void update(ll x,ll v)
    {
        while(x<=n)
        {
            tree[x]+=v;
            x+=lowbit(x);
        }
    }
    ll sum(ll x)
    {
        ll res=0;
        while(x>0)
        {
            res+=tree[x];
            x-=lowbit(x);
        }
        return res;
    }
    int main()
    {
        ios::sync_with_stdio(false);
        cin>>n>>m;
        ll k;
        for(ll i=1;i<=n;i++)
        {
            cin>>nm[i];
            update(i,nm[i]-nm[i-1]);
        }
        ll a,b,c,d;
        while(m--)
        {
            cin>>a;
            if(a==1)
            {
                cin>>b>>c>>d;
                update(b,d);
                update(c+1,-d);
            }
            else
            {
                cin>>b;
                cout<<sum(b)<<endl;
            }
        }
        cin.tie(0);
        return 0;
    }
  • 相关阅读:
    Android之vector代码修改颜色
    一个关于native sql的程序
    webdynpro 下拉列表控件
    webdynpro tree控件使用
    webdynpro MESSGAE
    webdynpro的select_option示例
    一个简单的webdynpro的ALV示例
    ALV前导零的问题
    自动流水号
    OO的ALV隐藏工具栏的form
  • 原文地址:https://www.cnblogs.com/Chri-K/p/13901404.html
Copyright © 2011-2022 走看看