题目链接:
http://poj.org/problem?id=3667
题意:
有一个线段,从1到n,下面m个操作,操作分两个类型,以1开头的是查询操作,以2开头的是更新操作
1 w 表示在总区间内查询一个长度为w的可用区间,并且要最靠左,能找到的话返回这个区间的左端点并占用了这个区间,找不到返回0
2 a len , 表示从单位a开始,清除一段长度为len的区间(将其变为可用,不被占用),不需要输出
题解:
线段树– 区间更新 区间合并 区间查询
lazy为-1表示没有更新到这个区间,所以不用pushdown; 为0表示这个区间没有被占用,所以传下去的长度就是当前区间的一半,左右各一半; 为1表示这个区间被占用了,给儿子区间的长度传成0就好了。
注意每次更新都要pushdown的是当前区间的长度
http://www.cnblogs.com/scau20110726/archive/2013/05/07/3065418.html 写的挺好
http://www.cnblogs.com/yewei/archive/2012/05/05/2484471.html 参考代码
代码:
#include <stdio.h>
#include <algorithm>
#include <cstring>
using namespace std;
typedef long long ll;
#define MS(a) memset(a,0,sizeof(a))
#define MP make_pair
#define PB push_back
const int INF = 0x3f3f3f3f;
const ll INFLL = 0x3f3f3f3f3f3f3f3fLL;
inline ll read(){
ll x=0,f=1;char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
return x*f;
}
//////////////////////////////////////////////////////////////////////////
const int maxn = 1e5+10;
struct node{
int l,r,lm,rm,mm,len,lazy;
void update(int val,int len){
lazy = val;
if(val) lm=rm=mm = 0;
else lm=rm=mm = len;
}
}tree[maxn<<2];
void pushup(int rt){
tree[rt].lm = tree[rt<<1].lm;
tree[rt].rm = tree[rt<<1|1].rm;
tree[rt].mm = max(max(tree[rt<<1].mm,tree[rt<<1|1].mm),tree[rt<<1].rm+tree[rt<<1|1].lm);
if(tree[rt<<1].lm == tree[rt<<1].len) tree[rt].lm = tree[rt<<1].lm + tree[rt<<1|1].lm;
if(tree[rt<<1|1].rm == tree[rt<<1|1].len) tree[rt].rm = tree[rt<<1].rm+tree[rt<<1|1].rm;
}
void pushdown(int rt, int len){
int lazyval = tree[rt].lazy;
if(lazyval != -1){
tree[rt<<1].lazy = tree[rt<<1|1].lazy = tree[rt].lazy;
if(lazyval) {
tree[rt<<1].lm=tree[rt<<1].rm=tree[rt<<1].mm = 0;
tree[rt<<1|1].lm=tree[rt<<1|1].rm=tree[rt<<1|1].mm = 0;
}else{
tree[rt<<1].lm = tree[rt<<1].rm = tree[rt<<1].mm = len-(len/2);
tree[rt<<1|1].lm = tree[rt<<1|1].rm = tree[rt<<1|1].mm = len/2;
}
tree[rt].lazy = -1;
}
}
void build(int rt,int l,int r){
tree[rt].l = l, tree[rt].r = r;
tree[rt].lm = tree[rt].rm = tree[rt].mm = tree[rt].len = r-l+1;
tree[rt].lazy = -1;
if(l != r){
int mid = (l+r)/2;
build(rt<<1,l,mid);
build(rt<<1|1,mid+1,r);
pushup(rt);
}
}
void update(int l,int r,int val,int rt){
int L = tree[rt].l, R = tree[rt].r;
if(l<=L && R<=r){
tree[rt].update(val,R-L+1);
return ;
}
pushdown(rt,R-L+1);
int mid = (L+R)/2;
if(l<=mid) update(l,r,val,rt<<1);
if(r>mid) update(l,r,val,rt<<1|1);
pushup(rt);
}
ll query(int rt,int len){
int L = tree[rt].l, R = tree[rt].r;
if(L==R)
return L;
pushdown(rt,R-L+1);
if(tree[rt<<1].mm >= len)
return query(rt<<1,len);
else if(tree[rt<<1].rm+tree[rt<<1|1].lm >= len)
return tree[rt<<1].r-tree[rt<<1].rm+1;
else if(tree[rt<<1|1].mm >= len)
return query(rt<<1|1,len);
else
return 0;
}
int main(){
int n = read(), m = read();
build(1,1,n);
while(m--){
int op = read();
if(op == 1){
int x = read();
int ans = query(1,x);
printf("%d\n",ans);
if(ans)
update(ans,ans+x-1,1,1);
}else{
int x=read(),len=read();
update(x,x+len-1,0,1);
}
}
return 0;
}