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

      first:

        单点修改,区间查询:

    #include<cstdio>
    #include<iostream>
    #include<cstring>
    using namespace std;
    #define maxn 500005
    int tree[maxn],n,m;
    int lowbit(int x)
    {
        return x & (-x);
    }
    void update(int x,int k)
    {
        while(x<=n)
        {
            tree[x]+=k;
            x+=lowbit(x);
        }
    }
    int query(int x)
    {
        int ans=0;
        while(x)
        {
            ans+=tree[x];
            x-=lowbit(x);
        }
        return ans;
    }
    int main()
    {
        scanf("%d%d",&n,&m);
        for(int i=1; i<=n; i++)
        {
            int x;
            scanf("%d",&x);
            update(i,x);
        }
        for(int i=1; i<=m; i++)
        {
            int op,x,y;
            scanf("%d%d%d",&op,&x,&y);
            if(op==1)
                update(x,y);
            else
                printf("%d
    ",query(y)-query(x-1));
        }
        return 0;
    }

      second:

       区间修改,单点查询:

    #include<cstdio>
    #include<iostream>
    using namespace std;
    #define maxn 5000005
    int tree[maxn],n,m;
    int lowbit(int x)
    {
        return x & (-x);
    }
    void update(int x,int k)
    {
        while(x<=n)
        {
            tree[x]+=k;
            x+=lowbit(x);
        }
    }
    int query(int x)
    {
        int ans=0;
        while(x)
        {
            ans+=tree[x];
            x-=lowbit(x);
        }
        return ans;
    }
    int main()
    {
        scanf("%d%d",&n,&m);
        int last=0;
        for(int i=1; i<=n; i++)
        {
            int x;
            scanf("%d",&x);
            update(i,x-last);
            last=x;
        }
        for(int i=1; i<=m; i++)
        {
            int op;
            int x,y,k;
            scanf("%d",&op);
            if(op==1)
            {
                scanf("%d%d%d",&x,&y,&k);
                update(x,k);
                update(y+1,-k);
            }
            else
            {
                scanf("%d",&x);
                printf("%d
    ",query(x));
            }
        }
        return 0;
    }

        

  • 相关阅读:
    map
    01背包和完全背包 POJ
    并查集 计算节点数量
    set
    map,vector,queue 图 综合运用
    并查集 hdu-1325 Is It A Tree?
    js中的ajax
    java算法
    MySql在Window上的安装
    微信开发账号要求
  • 原文地址:https://www.cnblogs.com/popo-black-cat/p/10343157.html
Copyright © 2011-2022 走看看