树状数组c++/java版

本文介绍了两种使用位运算实现的高效数据结构:Bit类中利用lowbit()优化树操作,而BIT类则展示了如何利用位操作简化查询和添加。这些技巧在信息技术中常用于高效的数据查询和更新,适用于计数和区间统计问题。
摘要由CSDN通过智能技术生成
class Bit{
private:
    int n;
    vector<int> tree;
public:
    Bit(int _n):
        n(_n),tree(_n+1) {}
    int lowbit(int x){
        return x&(-x);
    }
    void add(int x){
        for(int i=x;i<=n;i+=lowbit(i)) tree[i] += 1;
    }
    int query(int x){
        int ans = 0;
        for(int i=x;i;i-=lowbit(i)) ans += tree[i];
        return ans;
    }
    void print(){
        for(int i=1;i<=n;i++) cout << tree[i] << " ";
        cout << endl;
    }
    
};
class BIT {
    private int[] tree;
    private int n;

    public BIT(int n) {
        this.n = n;
        this.tree = new int[n + 1];
    }

    public static int lowbit(int x) {
        return x & (-x);
    }

    public int query(int x) {
        int ret = 0;
        while (x != 0) {
            ret += tree[x];
            x -= lowbit(x);
        }
        return ret;
    }

    public void add(int x) {
        while (x <= n) {
            ++tree[x];
            x += lowbit(x);
        }
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值