java - 线段树java实现

标签 java algorithm segment-tree

<分区>

您知道(二进制)segment tree 的良好实现吗?在 java ?

最佳答案

public class SegmentTree {
    public static class STNode {
        int leftIndex;
        int rightIndex;
        int sum;
        STNode leftNode;
        STNode rightNode;
    }

    static STNode constructSegmentTree(int[] A, int l, int r) {
        if (l == r) {
            STNode node = new STNode();
            node.leftIndex = l;
            node.rightIndex = r;
            node.sum = A[l];
            return node;
        }
        int mid = (l + r) / 2;
        STNode leftNode = constructSegmentTree(A, l, mid);
        STNode rightNode = constructSegmentTree(A, mid+1, r);
        STNode root = new STNode();
        root.leftIndex = leftNode.leftIndex;
        root.rightIndex = rightNode.rightIndex;
        root.sum = leftNode.sum + rightNode.sum;
        root.leftNode = leftNode;
        root.rightNode = rightNode;
        return root;
    }

    static int getSum(STNode root, int l, int r) {
        if (root.leftIndex >= l && root.rightIndex <= r) {
            return root.sum;
        }
        if (root.rightIndex < l || root.leftIndex > r) {
            return 0;
        }
        return getSum(root.leftNode, l, r) + getSum(root.rightNode, l, r);
    }

    /**
     * 
     * @param root
     * @param index index of number to be updated in original array 
     * @param newValue
     * @return difference between new and old values
     */
    static int updateValueAtIndex(STNode root, int index, int newValue) {
        int diff = 0;
        if(root.leftIndex==root.rightIndex && index == root.leftIndex) {
            // We actually reached to the leaf node to be updated
            diff = newValue-root.sum;
            root.sum=newValue;
            return diff;
        }
        int mid = (root.leftIndex + root.rightIndex) / 2;
        if (index <= mid) {
            diff= updateValueAtIndex(root.leftNode, index, newValue);
        } else {
            diff= updateValueAtIndex(root.rightNode, index, newValue);
        }
        root.sum+=diff;
        return diff;
    }
}

关于java - 线段树java实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/789489/

相关文章:

c++ - 如何使用 Boost.Geometry 检查一个环是否包含在另一个环中?

c# - 两种冒泡排序算法的区别

arrays - 将全为零的给定数组转换为目标数组

string - 通过对字符串进行某些操作来检查括号字符串是否平衡

java - 为什么 ByteArrayOutputStream.close() 抛出 IOException?

java - 使用 Apache POI 在 Word 文档中添加水印

java - 玩家移动方向逻辑

performance - 递归伪代码的时间复杂度

algorithm - 线段树范围最小查询

java - 使用操作更新另一个类中的实例变量