leetcode https://leetcode.cn/problems/count-integers-in-intervals/ 線段樹解決
阿新 • • 發佈:2022-05-15
leetccode count-integers-in-intervals 線段樹解決:
class CountIntervals {
Seg root;
public CountIntervals() {
root = new Seg(1, 1000000000);
}
public void add(int left, int right) {
root.add(left, right);
}
public int count() {
return root.cnt;
}
public static void main(String[] args) {
CountIntervals countIntervals = new CountIntervals();
System.out.println(countIntervals.count());
countIntervals.add(39, 44);
System.out.println(countIntervals.count());
countIntervals.add(13, 49);
System.out.println(countIntervals.count());
System.out.println(countIntervals.count());
countIntervals.add(47, 50);
}
class Seg {
int cl, cr;
int cnt;
boolean tag;
Seg l, r;
public Seg(final int cl, final int cr) {
this.cl = cl;
this.cr = cr;
// this.cnt = cr - cl + 1;
this.cnt = 0;
this.tag = false;
}
public void pushdown() {
if (this.tag) {
int mid = (cl + cr) >> 1;
if (this.l == null) {
this.l = new Seg(cl, mid);
}
if (this.r == null) {
this.r = new Seg(mid + 1, cr);
}
this.l.tag = true;
this.r.tag = true;
this.l.cnt = mid - cl + 1;
this.r.cnt = cr - mid;
}
}
public void pushup() {
/// this.cnt = 0;
this.tag = this.l.tag & this.r.tag;
this.cnt = this.l.cnt + this.r.cnt;
}
public void add(int L, int R) {
if (cl == L && cr == R) {
this.tag = true;
this.cnt = R - L + 1;
return;
}
if (this.tag) {
return;
}
// pushdown();
int mid = (cl + cr) >> 1;
if (this.r == null) {
this.r = new Seg(mid + 1, cr);
}
if (this.l == null) {
this.l = new Seg(cl, mid);
}
if (R <= mid) {
this.l.add(L, R);
} else {
if (L > mid) {//再右邊加入
this.r.add(L, R);
} else {
this.l.add(L, mid);
this.r.add(mid + 1, R);
}
}
pushup();
}
}
}
/**
* Your CountIntervals object will be instantiated and called as such:
* CountIntervals obj = new CountIntervals();
* obj.add(left,right);
* int param_2 = obj.count();
*/