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

    树状数组的作用和线段树基本一致,主要有更改和查询两种

    一、单点修改和区间查询(洛谷p3374

    代码

    #include<iostream>
    #include<cstdio>
    #include<cstring>
    #include<string>
    #include<algorithm>
    #include<cctype>
    #include<cmath>
    #include<cstdlib>
    #include<queue>
    #include<ctime>
    #include<vector>
    #include<set>
    #include<map>
    #include<stack>
    using namespace std;
    int c[2000000];
    int n;
    int lowbit(int x){
          return x&(-x);
    }
    void add(int pos,int x){
          while(pos<=n){
              c[pos]+=x;
              pos+=lowbit(pos);
          }
    }
    int sum(int x){
          int ans=0;
          while(x){
              ans+=c[x];
              x-=lowbit(x);
          }
          return ans;
    }
    int main()
    {     int m,i,j,k,x,y;
          cin>>n>>m;
          for(i=1;i<=n;i++){
              scanf("%d",&x);
              add(i,x);
          }
          for(i=1;i<=m;i++){
              scanf("%d%d%d",&k,&x,&y);
              if(k==1){
                  add(x,y);
              }
              else {
                  printf("%d ",sum(y)-sum(x-1));
              }
          }
          return 0;
    }
    二、区间修改和单点查询(洛谷p3368

    代码

    #include<iostream>
    #include<cstdio>
    #include<cstring>
    #include<string>
    #include<algorithm>
    #include<cctype>
    #include<cmath>
    #include<cstdlib>
    #include<queue>
    #include<ctime>
    #include<vector>
    #include<set>
    #include<map>
    #include<stack>
    using namespace std;
    int c[2000000];
    int n;
    int lowbit(int x){
          return x&(-x);
    }
    void add(int pos,int x){
          while(pos<=n){
              c[pos]+=x;
              pos+=lowbit(pos);
          }
    }
    int sum(int x){
          int ans=0;
          while(x){
              ans+=c[x];
              x-=lowbit(x);
          }
          return ans;
    }
    int main()
    {     int m,i,j,k,x,y,z,pre=0;
          cin>>n>>m;
          for(i=1;i<=n;i++){
              scanf("%d",&x);
              add(i,x-pre);
              pre=x;
          }
          for(i=1;i<=m;i++){
              scanf("%d",&k);
              if(k==1){
                  scanf("%d%d%d",&x,&y,&z);
                  add(x,z);
                  add(y+1,-z);
              }
              else {
                  scanf("%d",&x);
                  printf("%d ",sum(x));
              }
          }
          return 0;
    }

  • 相关阅读:
    地理大发现
    克里斯托弗·哥伦布
    2016. last day in office
    泰斯花粉阻隔剂 怎么使用
    ZT 螨虫知识2
    ZT 螨虫的话就不要跟狗多接触,狗的寄生虫很多,还有草地,
    expense KK [ɪkˋspɛns] DJ [iksˋpens]
    Windows 实战项目 001 文件扫描器 (01)
    017 系统内存信息 内存大小 空闲内存 5
    017 虚拟内存页面区块 4
  • 原文地址:https://www.cnblogs.com/yzxverygood/p/8371383.html
Copyright © 2011-2022 走看看