题目大意:n个房间编号1-n,现在有2个操作:操作1,给一个数d,表示要预定d间连续的房间,如果没有输出0,如果有,输出最小的起始房间号。操作2,给一个区间a,b,表示编号a到b的房间清房。
题目分析:线段树经典模型。这题并不难,不过要想清楚。我曾以为自己想清楚了,结果WA了一早上。。。
主要思路:在线段树每个节点维护3个变量:maxlen表示当前区间最大连续空房间数,l表示当前区间左连续房间数,r表示当前区间右连续空房间数。更新的时候成段更新,查询的时候分3步:1,如果左子区间的maxlen大于需要的房间数,到左子区间找;否则看左子区间的右连续房间数+右子区间的左连续房间数是否大于所需房间数;最后查找右子区间。
详情请见代码:
#include <iostream>
#include<cstdio>
#include<cstring>
using namespace std;
const int N = 500005;
#define Max(a,b) a>b?a:b
struct node
{
int maxlen;//当前区间最大连续空房间数量
int l,r;//当前区间左右最长连续空房间数量
}tree[N<<2];
int m,n;
void build(int num,int s,int e)
{
tree[num].l = tree[num].r = tree[num].maxlen = (e - s + 1);
if(s == e)
return;
int mid = (s + e)>>1;
build(num<<1,s,mid);
build(num<<1|1,mid + 1,e);
}
void insert(int num,int s,int e,int l,int r,int tag)
{
if(s == l && r == e)
{
tree[num].maxlen = tree[num].l = tree[num].r = (e - s + 1) * (!tag);
return;
}
int mid = (s + e)>>1;
if(tree[num].maxlen == 0)
{
tree[num].l = tree[num].r = 0;
tree[num<<1].maxlen = tree[num<<1|1].maxlen = 0;
tree[num<<1].l = tree[num<<1].r = 0;
tree[num<<1|1].l = tree[num<<1|1].r = 0;
}
if(tree[num].maxlen == e - s + 1)
{
tree[num].l = tree[num].r = e - s + 1;
tree[num<<1].maxlen = mid - s + 1;
tree[num<<1|1].maxlen = e - mid;
tree[num<<1].l = tree[num<<1].r = tree[num<<1].maxlen;
tree[num<<1|1].l = tree[num<<1|1].r = tree[num<<1|1].maxlen;
}
if(r <= mid)
insert(num<<1,s,mid,l,r,tag);
else
{
if(l > mid)
insert(num<<1|1,mid + 1,e,l,r,tag);
else
{
insert(num<<1,s,mid,l,mid,tag);
insert(num<<1|1,mid + 1,e,mid + 1,r,tag);
}
}
tree[num].maxlen = Max(tree[num<<1].maxlen,tree[num<<1|1].maxlen);
if(tree[num<<1].r + tree[num<<1|1].l > tree[num].maxlen)
tree[num].maxlen = tree[num<<1].r + tree[num<<1|1].l;
tree[num].l = tree[num<<1].l;
tree[num].r = tree[num<<1|1].r;
if(tree[num<<1|1].r == e - mid)
tree[num].r += tree[num<<1].r;
if(tree[num<<1].l == mid - s + 1)
tree[num].l += tree[num<<1|1].l;
}
int query(int num,int s,int e,int need)
{
if(tree[num].maxlen < need)
return 0;
if(tree[num].maxlen == e - s + 1)//此处如果判断是叶子节点就会WA,但是自己做的很多数据测不出来。。。
return s;//因为我们一直偏左找,最后返回一个值,如果判断叶子节点的话,可能一个区间会被拆成多个叶子节点,就会出错
int mid = (s + e)>>1;
if(tree[num<<1].maxlen >= need)
return query(num<<1,s,mid,need);
if(tree[num<<1].r + tree[num<<1|1].l >= need)
{
return mid - tree[num<<1].r + 1;
}
if(tree[num<<1|1].maxlen >= need)
return query(num<<1|1,mid + 1,e,need);
return 0;
}
int main()
{
int op,a,b;
while(~scanf("%d%d",&n,&m))
{
build(1,1,n);
while(m --)
{
scanf("%d",&op);
if(op == 1)
{
scanf("%d",&a);
int ans = query(1,1,n,a);
printf("%d\n",ans);
if(ans)
insert(1,1,n,ans,ans + a - 1,1);
}
else
{
scanf("%d%d",&a,&b);
insert(1,1,n,a,a + b - 1,0);
}
}
}
return 0;
}
//1708K 485MS
/*
10 6
1 3
1 2
1 3
2 4 2
1 2
10 6
1 4
1 3
2 2 5
1 3
1 3
1 1
10 10
1 4
1 3
2 2 5
1 3
1 3
1 1
1 1
1 1
1 1
1 1
10 4
1 4
1 2
2 2 5
1 4
1377 6
1 368
1 448
1 293
2 148 64
2 216 163
1 41
1 2
1 1
1 1
*/