树状数组(区间修改,单点查询)

这里介绍树状数组+差分思想,算是对下面大神的补充吧。

何为差分现在我们有一个从小到大的数列a[]

a{1,3,6,8,9};

然后还有一个差分数组b[]

b{1,2,3,2,1}

相信某些小伙伴已经看出端倪了..这里b[i]=a[i]-a[i-1],我令a[0]=0,故b[1]=a[1]。

拥有了b数组,我们就可以很简单的求出bit[]中任意一个数,只需bit[i]=sigma(k=1to i) b[k](这个很好推吧..)

我觉得现在该有人说我zz了..何必不直接查询a[i]而是找这么麻烦一个方法..这里我们转回正题!

别忘了,题目要我们进行区间修改..我们知道,树状数组对于单点值的修改十分方便(不懂的去看树状数组1),对于区间的修改就比较尴尬..

而我们又不想敲死长的线段树..怎么办呢,这时候差分就显出优势还是上面的a[]和b[],现在我们使区间[2,4]的所有数均+2

a[]/b[]变为

a{1,5,8,10,9}

b{1,4,3,2,-1}

 

事实上,这里只有b[2]和b[5]发生了变化,因为区间内元素均增加了同一个值,所以b[3],b[4]是不会变化的。

这里我们就有了第二个式子:对于区间[x,y]的修改(增加值为d)在b数组内引起变化的只有 b[x]+=d,b[y+1]-=d。(这个也很好推的..)

这样,我们就把树状数组的软肋用差分解决了。(摘自http://blog.csdn.net/largecub233/article/details/56666971

附题目一道(hud1556:http://acm.hdu.edu.cn/showproblem.php?pid=1556

还有代码:

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <cctype>
#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#include <queue>
#include <map>
#include <set>
#include <sstream>
#include<iomanip>
using namespace std;
typedef long long ll;
#define REW(a,b) memset(a,b,sizeof(a))
#define inf int(0x3f3f3f3f)
#define mod int(1e9+7)
#define P pair<int,int>
#define pi acos(-1)
inline int read()
{
    int X=0,w=0; char ch=0;
    while(!isdigit(ch)) {w|=ch=='-';ch=getchar();}
    while(isdigit(ch)) X=(X<<3)+(X<<1)+(ch^48),ch=getchar();
    return w?-X:X;
}
int n,a[100008];
int sum(int x)
{
    int ans=0;
    while(x>0) ans+=a[x],x-=x&-x;
    return ans;
}
void add(int x,int y) {while(x<=n) a[x]+=y,x+=x&-x;}
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    while(cin>>n&&n)
    {
        REW(a,0);
        int e=n;
        while(e--)
        {
            int q,w;
            q=read(),w=read();
            add(q,1);
            add(w+1,-1);
        }
        for(int i=1;i<n;i++)
        {
            cout<<sum(i)<<" ";
        }
        cout<<sum(n)<<endl;
    }
    return 0;
}

 

 

 

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值