zoukankan      html  css  js  c++  java
  • 树状数组模板2(洛谷例题P3368)(区间修改+单点查询)

    例题:https://www.luogu.org/problem/show?pid=3368

    上网看了别人家的讲解老半天。。。后来发现看的是区间修改加区间查询。。。。

    在树状数组的基础加上的差分在程序中具体有写。。

    程序:

    #include<iostream>
    
    #include<cstdio>
    #include<cstdlib>
    using namespace std;
    int ch,x,y,z,last,n,m,c[1000000];
    int lowbit(int x)
    {
      return (x&-x);
    }
    void update(int x,int y)
    {
      while (x<=n)
      {
          c[x]+=y;
          x+=lowbit(x);
      }
    }
    int query(int x)
    {
      int ans=0;
      while (x>0)
      {
        ans+=c[x];
        x-=lowbit(x);
      }
      return ans;
    }
    int main()
    {
        scanf("%d%d",&n,&m);
        for (int i=1;i<=n;i++)
        {
          scanf("%d",&x);
          update(i,x-last);
    //这里运用了差分思想,假设原本的数据存在a数组中,
    //那么c数组储存的就是c[i]=a[i]-a[i-1],如果c[1]=a[1],那么很明显
    //a[i]=c[i]+c[i-1]+c[i-2]+...+c[2]+c[1].
    //这样我们每次单点查询的时候只要加上c数组的前缀就可以了。
          last=x;
        }
        for (int i=1;i<=m;i++)
        {
          scanf("%d",&ch);
          if (ch==1)
          {
              scanf("%d%d%d",&x,&y,&z);
              update(x,z);
              update(y+1,-z);
          }
          else 
          {
              scanf("%d",&x);
              printf("%d
    ",query(x));
          }
        }
    }
  • 相关阅读:
    hp_jetdirect 9100漏洞检测
    fenghuangscannerV3 EXE版本
    计划:6.10
    [PY]进制转换
    OpenStack 制作镜像
    Kernel 问题小记
    Ubuntu 问题小记
    Git 常用命令
    OpenStack 构建单测环境
    SDN 杂谈
  • 原文地址:https://www.cnblogs.com/2014nhc/p/6368774.html
Copyright © 2011-2022 走看看