例题: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\n",query(x));
      }
    }
}

 

posted on 2017-02-05 22:44  nhc2014  阅读(837)  评论(0编辑  收藏  举报