题解 P2161 【[SHOI2009]会场预约】
CodyTheWolf · · 题解
开头小广告:自己做的一个模板库OwO
分析:
这道题两种主流算法是平衡树(或者set)和线段树染色,前者大同小异,不过后者就有很多不同的写法了。貌似大家写的有点复杂有好多数组,那我这边写一个比较简单易懂的:
算法:
我们把每次Ai 操作看成在线段树上s 和t 之间涂上颜色i,开两个数组s[i] 和t[i] 表示第i 个颜色的起始和结束以便于我们后面的查询
线段树上只用两个数组:color 代表区间的颜色,tag 是懒标记。(如果一时没有明白可以想成最普通的区间线段树加法)
这里的color,我们设-1为杂色,0为无色,大于0为颜色。在PushUp的时候,如果color[lson]==color[rson] 是没有问题的,但是当:
color[lson]!=color[rson] &&color[lson]!=0 &&color[rson]!=0
(说人话就是左右儿子颜色不同且两个都是有颜色的,而不是一个是白色)
时,我们只需再往下多走一个区间就行了,因为当区间左右端点重合,只有一个位置,也只有一个颜色,不可能还是-1。
所以对于A 操作,我们只需要在线段树上查询询问的区间[x,y] ,并在查询的时候在全局开数组,记录一下有哪几个颜色(记得处理过的颜色标记一下,因为颜色只会出现一次,不需要也不能重复删除)。
对于一个颜色c ,我们在线段树上把s[c]->t[c] 全部修改成0即可,记得打懒标记。
添加的区间直接在线段树上修改成对应的编号即可,这里的两个操作是可以共用一个函数的(在我的程序里就是Update函数)
复杂度分析:
每个区间只会被插入一次和删除一次,因此复杂度是O(nlogn)
CODE
线段树直接封装好了,比较容易看懂XD
// luogu-judger-enable-o2
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
const int MAXN = 1e5 + 5, MAXQ = 2e5 + 5, N = 1e5;
int colors[MAXQ], colort[MAXQ];
int queue[MAXQ], tail;
bool tag[MAXQ];
int n, sum = 0;
char opt[3];
#define mid ((x + y) >> 1)
#define lson (pst << 1)
#define rson (pst << 1 | 1)
//线段树
struct SegmentTree
{
int color[MAXN << 2], tag[MAXN << 2];
inline void PushUp(int pst)
{
if (color[lson] == color[rson])
color[pst] = color[lson];
else if (!color[lson] || !color[rson])
color[pst] = color[lson] + color[rson];//直接加起来是因为一个是0,加起来肯定是另外一个(FHQ_TREAP的写法)
else
color[pst] = -1;
return;
}
inline void PushDown(int pst)//非常普通的下放
{
if (tag[pst])
{
color[lson] = color[rson] = tag[pst];
tag[lson] = tag[rson] = tag[pst];
tag[pst] = 0;
}
return;
}
inline void Query(int x, int y, int pst, int l, int r)
{
if (y < l || x > r)
return;
if (l <= x && y <= r && (~color[pst]))//不是杂色且符合区间
{
if (color[pst])
queue[++tail] = color[pst];//queue是用来记录颜色的
return;
}
PushDown(pst);
Query(x, mid, lson, l, r), Query(mid + 1, y, rson, l, r);
PushUp(pst);
return;
}
inline void Update(int x, int y, int pst, int l, int r, int k)//非常普通的修改操作,和区间线段树加法没什么区别
{
if (y < l || x > r)
return;
if (l <= x && y <= r)
{
color[pst] = tag[pst] = k;
return;
}
PushDown(pst);
Update(x, mid, lson, l, r, k), Update(mid + 1, y, rson, l, r, k);
PushUp(pst);
return;
}
} ST;
signed main(void)
{
scanf("%d", &n);
for (int i = 1; i <= n; i++)
{
scanf("%s", opt);
if (opt[0] == 'A')
{
scanf("%d %d", colors + i, colort + i);
tail = 0;//记得让tail归0
ST.Query(1, N, 1, colors[i], colort[i]);
int cnt = 0;//删除的个数
for (int i = 1; i <= tail; i++)
if (!tag[queue[i]])//tag用来标记颜色是否被删除
{
int s = colors[queue[i]], t = colort[queue[i]];
ST.Update(1, N, 1, s, t, 0);
tag[queue[i]] = true;
cnt++;
}
ST.Update(1, N, 1, colors[i], colort[i], i);
printf("%d\n", cnt);
sum = sum - cnt + 1;
}
if (opt[0] == 'B')
printf("%d\n", sum);//sum就是当前还有的区间数咯~
}
return 0;
}