LeetCode 731. 我的日程安排表 II**

具体思路:

线段树区间最大值问题;

具体代码:

struct node{
    int ln,rn,maxn,val,add;
    node(){
        ln=0;
        rn=0;
        add=0;
        val=0;
    }
};

class MyCalendarTwo {
public:
    MyCalendarTwo() {
        n=1e9;
        m=1e6;
        cnt=1;
        tree.resize(m);
    }

    void create(int root){
        if(tree[root]==nullptr){
            tree[root]=new node();
        }
        if(tree[root]->ln==0){
            //左节点未开;
            tree[root]->ln=++cnt;
            tree[tree[root]->ln]=new node();
        }
        if(tree[root]->rn==0){
            tree[root]->rn=++cnt;
            tree[tree[root]->rn]=new node();
        }
    }

    void pushup(int root){
        tree[root]->val=max(tree[tree[root]->ln]->val,tree[tree[root]->rn]->val);
    }

    void pushdown(int root){
        tree[tree[root]->ln]->add+=tree[root]->add;
        tree[tree[root]->rn]->add+=tree[root]->add;
        tree[tree[root]->ln]->val+=tree[root]->add; 
        tree[tree[root]->rn]->val+=tree[root]->add;
        tree[root]->add=0;
    }

    int query(int root,int l,int r,int lc,int rc){
        if(l<=lc&&rc<=r){
            return tree[root]->val;
        }
        create(root);
        pushdown(root);
        int mid=lc+(rc-lc)/2;
        int ret=0;
        if(l<=mid){
            ret=max(ret,query(tree[root]->ln, l, r, lc, mid));
        }
        if(mid<r){
            ret=max(ret,query(tree[root]->rn, l, r, mid+1, rc));
        }
        return ret;
    }


    void update(int root,int l,int r,int lc,int rc){
        if(l<=lc&&rc<=r){
            tree[root]->val++;
            tree[root]->add++;
            return;
        }
        create(root);
        pushdown(root);
        int mid=lc+(rc-lc)/2;
        if(l<=mid)
            update(tree[root]->ln, l, r, lc, mid);
        if(r>mid)
            update(tree[root]->rn,l, r, mid+1, rc);
        pushup(root);
    }
    
    bool book(int start, int end) {
        if(query(1, start+1, end, 1, n+1)>=2)
            return false;
        update(1, start+1, end,1, n+1);
        return true;
    }
private:
    vector<node*> tree;
    int n;
    int m;
    int cnt;
};

/**
 * Your MyCalendarTwo object will be instantiated and called as such:
 * MyCalendarTwo* obj = new MyCalendarTwo();
 * bool param_1 = obj->book(start,end);
 */```

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值