一本通提高篇树状数组做题集

本文介绍了树状数组的三种基础操作,并提供了详细的代码实现。接着通过四道不同难度的题目,包括数星星、校门外的树、清点人数等,深入讲解了树状数组在实际问题中的应用,适合初学者巩固和提高。
摘要由CSDN通过智能技术生成

前奏

做树状数组的题之前,需要做三道板子题:

板子题1——单点修改,区间查询

板子题就不写题解了哈╮(╯▽╰)╭

代码
#include<cstdio>
#include<iostream>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<cstdlib>
#define int long long
using namespace std;
int n,q,a[1000005],c[1000005];
void update(int t,int v)
{
    for (int x=t; x<=n; x+=x&-x) c[x]+=v;
}
int getsum(int t)
{
    int ans=0;
    for (int x=t; x; x-=x&-x) ans+=c[x];
    return ans;
}
signed main()
{
    scanf("%lld%lld",&n,&q);
    for (int i=1; i<=n; i++) scanf("%lld",&a[i]),update(i,a[i]);
    for (int i=1; i<=q; i++){
        int x,l,r;
        scanf("%lld%lld%lld",&x,&l,&r);
        if (x==1) update(l,r);
        if (x==2) printf("%lld\n",getsum(r)-getsum(l-1));
    }
    return 0;
}

板子题2——区间修改,单点查询
代码
#include<cstdio>
#include<iostream>
#include<iostream>
#include<cmath>
#include<cstring>
#include<algorithm>
#define int long long
using namespace std;
int n,q,a[1000005],c[1000005];
void update(int x,int v)
{
    for (; x<=n; x+=x&-x) c[x]+=v;
}
int getsum(int x)
{
    int sum=0;
    for (; x>0; x-=x&-x) sum+=c[x];
    return sum;
}
signed main()
{
    scanf("%lld",&n);
    scanf("%lld",&q);
    int last=0
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值