首页 > 编程语言 > 详细

树状数组模板2(洛谷例题P3368)(区间修改+单点查询)

时间:2017-02-05 23:53:11      阅读:294      评论:0      收藏:0      [点我收藏+]

例题: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));
      }
    }
}

 

树状数组模板2(洛谷例题P3368)(区间修改+单点查询)

原文:http://www.cnblogs.com/2014nhc/p/6368774.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!