HDU-3667 Hotel 线段树 经典空间合并

http://poj.org/problem?id=3667

经典线段树,不解释了。

代码如下:

#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <algorithm>
#define MAXN 50000
using namespace std;

struct
{
int l, r;
int lmax, rmax, max, cover;
}seg[MAXN*4];

void build(int f, int l, int r)
{
int mid = l+r >> 1;
seg[f].l = l, seg[f].r = r;
seg[f].lmax = seg[f].rmax = seg[f].max = r-l+1;
seg[f].cover = 0;
if (r > l)
{
build(f<<1, l, mid);
build(f<<1|1, mid+1, r);
}
}

void up(int f)
{
seg[f].lmax = seg[f<<1].lmax;
seg[f].rmax = seg[f<<1|1].rmax;
if (seg[f<<1].cover == 0)
seg[f].lmax += seg[f<<1|1].lmax;
if (seg[f<<1|1].cover == 0)
seg[f].rmax += seg[f<<1].rmax;
seg[f].max = max(seg[f<<1].max, seg[f<<1|1].max);
seg[f].max = max(seg[f].max, seg[f<<1].rmax+seg[f<<1|1].lmax);
if (seg[f<<1].cover == seg[f<<1|1].cover)
seg[f].cover = seg[f<<1].cover;
else
seg[f].cover = -1;
}

void modify(int f, int l, int r, int val)
{
int mid = seg[f].l+seg[f].r >> 1;
if (seg[f].l == l && seg[f].r == r)
{
seg[f].cover = val;
if (val == 0)
seg[f].lmax = seg[f].rmax = seg[f].max = r-l+1;
else
seg[f].lmax = seg[f].rmax = seg[f].max = 0;
}
else if (seg[f].r > seg[f].l)
{
if (seg[f].cover == 0)
{
seg[f<<1].cover = seg[f<<1|1].cover = 0;
seg[f<<1].lmax = seg[f<<1].rmax = seg[f<<1].max = seg[f<<1].r-seg[f<<1].l+1;
seg[f<<1|1].lmax = seg[f<<1|1].rmax = seg[f<<1|1].max = seg[f<<1|1].r-seg[f<<1|1].l+1;
seg[f].cover = -1;
}
else if (seg[f].cover == 1)
{
seg[f<<1].cover = seg[f<<1|1].cover = 1;
seg[f<<1].lmax = seg[f<<1].rmax = seg[f<<1].max = 0;
seg[f<<1|1].lmax = seg[f<<1|1].rmax = seg[f<<1|1].max = 0;
seg[f].cover = -1;
}
if (r <= mid)
modify(f<<1, l, r, val);
else if (l > mid)
modify(f<<1|1, l, r, val);
else
{
modify(f<<1, l, mid, val);
modify(f<<1|1, mid+1, r, val);
}
up(f);
}
}

int query(int f, int size)
{
if (seg[f].max < size)
return 0;
else if (seg[f].lmax >= size)
return seg[f].l;
else if (seg[f<<1].max >= size)
return query(f<<1, size);
else if (seg[f<<1].rmax+seg[f<<1|1].lmax >= size)
return seg[f<<1].r-seg[f<<1].rmax+1;
else
return query(f<<1|1, size);
}

int main()
{
int N, M, op, size, s, e, pos;
while (scanf("%d %d", &N, &M) == 2)
{
build(1, 1, N);
while (M--)
{
scanf("%d", &op);
if (op == 1)
{
scanf("%d", &size);
pos = query(1, size);
printf("%d\n", pos);
if (pos != 0) // 执行占用命令
modify(1, pos, pos+size-1, 1);
}
else
{
scanf("%d %d", &s, &e);
modify(1, s, s+e-1, 0);
}
}
}
return 0;
}



你可能感兴趣的:(HDU)