数据结构与算法-IndexTree


public class Code_IndexTree {
    public static void main(String[] args) {
        int N = 100;
        int V = 100;
        int testTime = 2000000;
        IndexTree tree = new IndexTree(N);
        Right test = new Right(N);
        System.out.println("test begin");
        for (int i = 0; i < testTime; i++) {
            int index = (int) (Math.random() * N) + 1;
            if (Math.random() <= 0.5) {
                int add = (int) (Math.random() * V);
                tree.add(index, add);
                test.add(index, add);
            } else {
                if (tree.sum(index) != test.sum(index)) {
                    System.out.println("Oops!");
                }
            }
        }
        System.out.println("test finish");
    }

    public static class IndexTree{
        private int[] tree;
        private int N;

        public IndexTree(int size){
            N = size;
            tree = new int[size + 1];
            System.out.println("constructor");
        }

        // 求 1~index的累加和是多少
        public int sum(int index){
            int ret = 0;
            while(index > 0){
                ret += tree[index];
                index -= (index & -index); // 每次去掉二进制形式中最右侧的1
            }
            return ret;
        }

        /*
        index:          0011000
        index & -index: 0001000
        * */
        public void add(int index, int d){
            // index加上数d后,其他受影响的下标也要相应修改
            while(index <= N){
                tree[index] += d;
                index += index & -index; // 取出index的二进制形式最右侧的1
            }
        }
    }

    public static class Right {
        private int[] nums;
        private int N;

        public Right(int size) {
            N = size + 1;
            nums = new int[N + 1];
            System.out.println("constructor_right");
        }

        public int sum(int index) {
            int ret = 0;
            for (int i = 1; i <= index; i++) {
                ret += nums[i];
            }
            return ret;
        }

        public void add(int index, int d) {
            nums[index] += d;
        }

    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值