import java.util.*;
/**
* @author xnl
* @Description:
* @date: 2022/7/19 21:41
*/
public class Solution {
public static void main(String[] args) {
Solution solution = new Solution();
MyCalendarTwo2 my = new MyCalendarTwo2();
System.out.println(my.book(10, 20));
System.out.println(my.book(50, 60));
System.out.println(my.book(10, 40));
System.out.println(my.book(5, 15));
System.out.println(my.book(5, 10));
System.out.println(my.book(25, 55));
}
}
/**
* 暴力
*/
class MyCalendarTwo {
List<int[]> booked; // 已经预定的
List<int[]> overlaps; // 重叠的
public MyCalendarTwo() {
booked = new ArrayList<>();
overlaps = new ArrayList<>();
}
public boolean book(int start, int end) {
for (int[] overlap : overlaps) {
int left = overlap[0], right = overlap[1];
// 存在这个区间
if (left < end && start < right){
return false;
}
}
for (int[] ints : booked) {
int left = ints[0], right = ints[1];
if (left < end && start < right){
overlaps.add(new int[]{Math.max(left, start), Math.min(right, end)});
}
}
booked.add(new int[]{start, end});
return true;
}
}
// 分叉数组
class MyCalendarTwo2 {
TreeMap<Integer, Integer> treeMap;
public MyCalendarTwo2() {
treeMap = new TreeMap<>();
}
public boolean book(int start, int end) {
int ans = 0;
int maxBook = 0;
treeMap.put(start, treeMap.getOrDefault(start, 0) + 1);
treeMap.put(end, treeMap.getOrDefault(end, 0) - 1);
for (Map.Entry<Integer, Integer> entry : treeMap.entrySet()) {
Integer value = entry.getValue();
maxBook += value;
ans = Math.max(maxBook, ans);
if (maxBook > 2){
// 去掉当前结果
treeMap.put(start, treeMap.getOrDefault(start, 0) - 1);
treeMap.put(end, treeMap.getOrDefault(end, 0) + 1);
return false;
}
}
return true;
}
}
/**
* 线段树
*/
class MyCalendarTwo3 {
class Node{
Node ls, rs;
int max, add;
}
int N = (int)1e9;
Node root= new Node();
void update(Node node, int lc, int rc, int l, int r, int v){
// 到达根节点
if (l <= lc && rc <= r ){
node.add += v;
node.max += v;
return;
}
pushdown(node);
int mid = lc + rc >> 1;
// 开左边的点
if (l <= mid){
update(node.ls, lc, mid, l, r, v);
}
// 开右边的点
if (r > mid){
update(node.rs, mid + 1, rc, l, r, v);
}
pushup(node);
}
int query(Node node, int lc, int rc, int l, int r){
// 找到了结果
if (l <= lc && rc <= r){
return node.max;
}
pushdown(node);
int mid = lc + rc >> 1, ans = 0;
if (l <= mid){
ans = query(node.ls, lc, mid, l, r);
}
if (r > mid){
ans = Math.max(query(node.rs, mid + 1, rc, l, r), ans );
}
return ans;
}
void pushdown(Node node){
if (node.ls == null){
node.ls = new Node();
}
if (node.rs == null){
node.rs = new Node();
}
// 懒加载因子
int add = node.add;
node.ls.max += add;
node.rs.max += add;
node.ls.add += add;
node.rs.add += add;
// 删除加载因子
node.add = 0;
}
void pushup(Node node){
node.max = Math.max(node.ls.max, node.rs.max);
}
public boolean book(int start, int end) {
if (query(root, 0, N, start, end -1) >= 2){
return false;
}
update(root, 0, N, start, end - 1, 1);
return true;
}
}