【732. 我的日程安排表 III】線段樹求解
阿新 • • 發佈:2022-06-06
class MyCalendarThree { public static void main(String[] args) { MyCalendarThree myCalendarThree = new MyCalendarThree(); System.out.println( myCalendarThree.book(10,20) ); System.out.println(myCalendarThree.book(50,60)); System.out.println(myCalendarThree.book(10,40)); System.out.println(myCalendarThree.book(5,15)); System.out.println(myCalendarThree.book(5,10)); System.out.println(myCalendarThree.book(25,55)); } class Seg{ int cl,cr; Seg left,right; int cnt; int max; public Seg(int l,int r){ this.cl = l; this.cr = r;this.cnt = 0; this.max = 0; } public void pushdown(){ int mid = (cl+cr)/2; if( this.left == null){ this.left = new Seg(cl,mid); } if(this.right == null){ this.right = new Seg(mid+1,cr); }if( this.cnt == 0){ return; } this.left.max += this.cnt; this.right.max += this.cnt; this.left.cnt += this.cnt; this.right.cnt += this.cnt; this.cnt = 0; } public void add(int l,int r){ if(cl == l &&cr == r){ this.cnt++; this.max++; return; } pushdown(); int mid = (cl+cr)/2; if( r<=mid){ this.left.add(l,r); }else{ if(l>mid){ this.right.add(l,r); }else{ this.left.add(l,mid); this.right.add(mid+1,r); } } //pushup 啥也不做 pushup(); } public void pushup(){ this.max = Math.max(this.left.max,this.right.max); } public int search(int l,int r){ if(cl ==l &&cr == r){ return this.max; } pushdown(); int mid = (cl+cr)/2; int ans ; if(r<=mid){ ans = this.left.search(l,r); }else{ if(l>mid){ ans = this.right.search(l,r); }else{ int val1 = this.left.search(l,mid); int val2 = this.right.search(mid+1,r); ans = Math.max(val1,val2); } } pushup(); return ans; } } Seg seg; int k ; public MyCalendarThree() { seg = new Seg(0,1000000000); k = 0; } public int book(int start, int end) { seg.add(start,end-1); int val = seg.search(start,end-1); if(val > k){ k = val; } return k; } } /** * Your MyCalendarThree object will be instantiated and called as such: * MyCalendarThree obj = new MyCalendarThree(); * int param_1 = obj.book(start,end); */