题意:有编号为1~n的n个房间,有两种询问
1.有人来订连续的k间房,有的话返回第一间房的编号,否则返回0。
2.有人退连续的从a开始的连续的k间房。
解法:与之前做过的poj2750(线段树+动态规划)类似,就是在线段树上,记录每个区间的3个信息
1.该区间最大的连续空房数
2.该区间从最左边起的最大的连续空房数
3.该区间从最右边起的最大的连续空房数
根据以上三个信息,每个非叶结点的信息都可以由它的左右儿子更新得到了。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
using namespace std;
#define MAXN 50005
int total[MAXN<<2], col[MAXN<<2], lsum[MAXN<<2], rsum[MAXN<<2];
void PushUp(int l, int r, int rt) {
int m = (l + r) >> 1, lson = rt<<1, rson = rt<<1|1;
total[rt] = max(lsum[rson]+rsum[lson], max(total[lson], total[rson]));
if (lsum[lson] == m - l + 1) lsum[rt] = lsum[lson] + lsum[rson];
else lsum[rt] = lsum[lson];
if (rsum[rson] == r - m) rsum[rt] = rsum[rson] + rsum[lson];
else rsum[rt] = rsum[rson];
}
void PushDown(int l, int r, int rt)
{
int m = (l + r) >> 1, lson = rt << 1, rson = rt<<1|1;
total[lson] = lsum[lson] = rsum[lson] = (col[rt] == 1 ? m - l + 1 : 0);
total[rson] = lsum[rson] = rsum[rson] = (col[rt] == 1 ? r - m : 0);
col[lson] = col[rson] = col[rt];
col[rt] = 0;
}
void Build(int l, int r, int rt) {
lsum[rt] = rsum[rt] = total[rt] = r - l + 1;
if (l == r) return;
int m = (l + r) >> 1;
Build(l, m, rt<<1);
Build(m+1, r, rt<<1|1);
}
void Update(int L, int R, int c, int l, int r, int rt) {
if (l >= L && r <= R) {
col[rt] = c;
total[rt] = lsum[rt] = rsum[rt] = (c == 1 ? r - l + 1 : 0);
return;
}
if (col[rt]) PushDown(l, r, rt);
int m = (l + r) >> 1;
if (m >= L) Update(L, R, c, l, m, rt<<1);
if (m < R) Update(L, R, c, m+1, r, rt<<1|1);
PushUp(l, r, rt);
}
int Query(int l, int r, int rt, int c) {
if (total[rt] < c) return 0;
if (l == r) return l;
if (col[rt]) PushDown(l, r, rt);
int m = (l + r) >> 1, lson = rt<<1, rson = rt<<1|1;
if (total[lson] >= c) return Query(l, m, lson, c);
else if (rsum[lson]+lsum[rson] >= c) return m - rsum[lson] + 1;
else return Query(m+1, r, rson, c);
}
int main()
{
int n, m, op, a, b;
scanf ("%d%d", &n, &m);
memset(col, 0, sizeof (col));
Build(1, n, 1);
while (m--) {
scanf ("%d", &op);
if (op == 1) {
scanf ("%d", &a);
int res = Query(1, n, 1, a);
printf ("%d\n", res);
if (res) Update(res, res+a-1, -1, 1, n, 1);
}
else {
scanf ("%d %d", &a, &b);
Update(a, a+b-1, 1, 1, n, 1);
}
}
return 0;
}