线段树-入门
来源:互联网 发布:成吉思汗征服月球知乎 编辑:程序博客网 时间:2024/04/29 03:13
-
- public class SegmentTreeLearn {
- public static void main(String[] args) {
- SegmentTree tree = new SegmentTree(0,7);
- int[][] segments = {
- {2, 5},
- {4, 6},
- {0, 7}
- };
- int[] targets = {2, 4, 7};
- for (int i = 0, len = segments.length; i < len; i++) {
- int[] segment = segments[i];
- tree.insert(segment[0], segment[1]);
- }
- for(int target : targets) {
- System.out.println(target + ":" + tree.caculateExistingTimes(target));
- }
- }
- }
- class SegmentTree {
- private class Segment {
- int left;
- int right;
- int count;
- Segment leftChild;
- Segment rightChild;
- }
- private Segment root;
- public SegmentTree (int left,int right) {
- root = new Segment();
- build(root, left, right);
- }
- public void insert(int left,int right) {
- insert(root, left, right);
- }
- public int caculateExistingTimes(int target) {
- return caculateExistingTimes(root, target);
- }
- private int caculateExistingTimes(Segment root,int target) {
- int result = 0;
- while( root.left != root.right) {
- int rootMid = root.left + (root.right - root.left) /2;
- result += root.count;
- if (target <= rootMid) {
- root = root.leftChild;
- } else if (target > rootMid) {
- root = root.rightChild;
- }
- }
- return result;
- }