pku3667 Hotel

查询最左端的连续空房间,思想是二分,不过是在线段树上做的二分,所以线段树结点上需要记录一些附加信息,为二分提供条件

又WA了几次才过的,总结经验就是:
更新区间的过程,递归进入子节点前,如果父节点被完全覆盖(在之前的操作中整个区间被修改为住人或空房),那么要相应地修改子节点;从子节点回溯出来后,根据子节点的情况更新父节点。

查询区间的过程也是,要考虑父节点被完全覆盖的情况,这时就不用再往下递归了


#include <cstdio>

const int maxN = 50000 + 5;
struct node_t {
int ll, mm, rr;
} tree[maxN * 3];

int max3(int x, int y, int z)
{
x = x > y ? x : y;
x = x > z ? x : z;
return x;
}

int left, right;
bool checkIn;
void check(int low, int high, int node)
{
if (left <= low && high <= right) {
tree[node].ll = tree[node].mm = tree[node].rr = (checkIn ? 0 : high - low + 1);
} else if (left <= high && low <= right) {
node_t &lch = tree[node * 2], &rch = tree[node * 2 + 1];
int mid = (low + high) / 2;
if (tree[node].mm == high - low + 1)
{
lch.ll = lch.mm = lch.rr = mid - low + 1;
rch.ll = rch.mm = rch.rr = high - mid;
}
if ((tree[node].ll | tree[node].mm | tree[node].rr) == 0)
{
lch.ll = lch.mm = lch.rr = 0;
rch.ll = rch.mm = rch.rr = 0;
}
check(low, mid, node * 2);
check(mid + 1, high, node * 2 + 1);
tree[node].ll = lch.ll + (lch.ll == mid - low + 1 ? rch.ll : 0);
tree[node].rr = (rch.rr == high - mid ? lch.rr : 0) + rch.rr;
tree[node].mm = max3(lch.rr + rch.ll, lch.mm, rch.mm);
}
}

int need;
int find(int low, int high, int node)
{
if (tree[node].mm == high - low + 1 || (tree[node].ll | tree[node].mm | tree[node].rr) == 0) {
if (tree[node].mm >= need)
return low;
} else if (low < high) {
if (tree[node].ll >= need)
return low;
int mid = (low + high) / 2;
node_t &lch = tree[node * 2], &rch = tree[node * 2 + 1];
if (tree[node].mm >= need)
{
if (lch.mm >= need)
return find(low, mid, node * 2);
if (lch.rr + rch.ll >= need)
return mid - lch.rr + 1;
if (rch.mm >= need)
return find(mid + 1, high, node * 2 + 1);
}
if (tree[node].rr >= need)
return high - tree[node].rr + 1;
}
return 0;
}

int main()
{
int N, M, req, X, D;
scanf("%d%d", &N, &M);
left = 1, right = N, checkIn = false;
check(1, N, 1);
while (M--)
{
scanf("%d", &req);
if (req == 1) {
scanf("%d", &D);
need = D;
X = find(1, N, 1);
printf("%d\n", X);
if (X != 0)
{
left = X, right = X + D - 1, checkIn = true;
check(1, N, 1);
}
} else {
scanf("%d%d", &X, &D);
left = X, right = X + D - 1, checkIn = false;
check(1, N, 1);
}
}
return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值