题解 P3850 【[TJOI2007]书架】
写在前面的话:
这篇题解的做法是通俗易懂,儒雅随和。
大家可以在我的blog中进行查看。
下面进入正文。
Problem's Website
TJOI2007 书架
Solution
这是一道平衡树的好题,因为我暂时不会
首先关于
这道题要用到排名分裂,同样用到这种方法的还有另外一道同名题。
上面好像都是废话,下面是干货。
下面详细地说一下操作。
1.处理书的名称:
因为是字符串,所以我们用一个
string 类型的数组记录,用一个变量当做编号映射到每本书的名称。
温馨提示:注意数据范围,否则将惨遭
RE 。。。(好像就我这个菜鸡RE 了)
2.处理一开始就在书架上的书:
我们所说的“排名”即当前这本书的上面有几本书,所以对于最开始的书籍,我们只要
insert(i - 1, cnt); 即可(cnt即为映射的变量)
3.处理后来放入的书籍:
经过研究样例,我们发现:插入一个位置为
x 的书,原本的第x 本到最后一本的位置都会+1 ,也就是,那么也就是说,插入后这本书的排名就为x ,所以就insert(x, cnt);
4.处理询问
要输出第
x 个位置书的名称,我们就相当于找到第x 个位置书映射的编号。
方法也很简单,我们首先以
x 为排名将树分裂成以r1, r2 为根的两棵树,再对r2 以1 为排名分裂成以r3, r4 为根的两棵树,这样r3 就成了一个节点,也就是要求的答案。
给个图让大家理解一下(对于
fhq-Treap ,不理解的时候画个图有事半功倍的效果):
别忘了最后合并回去。
相信大家对
所以下面代码就不解释了 (逃
Code
//Coded by dy.
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#define gc getchar()
#define pc(x) putchar(x)
#define re register
const int Maxn = 1e5 + 200 + 10;
using std :: string;
using std :: cin;
using std :: cout;
using std :: endl;
inline int sc() {
int xx = 0, ff = 1; char cch = gc;
while(!isdigit(cch)) {
if(cch == '-') ff = -1; cch = gc;
}
while(isdigit(cch)) {
xx = (xx << 1) + (xx << 3) + (cch ^ '0'); cch = gc;
}
return xx * ff;
}
inline void out(int x) {
if(x < 0)
pc('-'), x = -x;
if(x >= 10)
out(x / 10);
pc(x % 10 + '0');
}
struct fhq_Treap {
int ch[2];
int siz, val, dat;
}t[Maxn];
int n, m, cnt;
int rt, r1, r2, r3, r4, tot;
string s[Maxn];
inline void pushup(int id) {
t[id].siz = t[t[id].ch[0]].siz + t[t[id].ch[1]].siz + 1;
}
inline int cre(int r) {
t[++tot].siz = 1, t[tot].val = r, t[tot].dat = rand();
return tot;
}
inline void split(int id, int r, int &x, int &y) {
if(!id)
x = y = 0;
else {
if(r <= t[t[id].ch[0]].siz) {
y = id;
split(t[id].ch[0], r, x, t[id].ch[0]);
}
else {
x = id;
split(t[id].ch[1], r - t[t[id].ch[0]].siz - 1, t[id].ch[1], y);
}
pushup(id);
}
}
inline int merge(int x, int y) {
if(!x || !y)
return x + y;
if(t[x].dat < t[y].dat) {
t[x].ch[1] = merge(t[x].ch[1], y);
pushup(x);
return x;
}
t[y].ch[0] = merge(x, t[y].ch[0]);
pushup(y);
return y;
}
inline void insert(int r, int id) {
split(rt, r, r1, r2);
rt = merge(r1, merge(cre(id), r2));
}
inline void query(int r) {
split(rt, r, r1, r2);
split(r2, 1, r3, r4);
cout << s[t[r3].val] << endl;
rt = merge(r1, merge(r3, r4));
}
int main() {
srand(20041029);
n = sc();
for(re int i = 1; i <= n; ++i) {
cin >> s[++cnt];
insert(i - 1, cnt);
}
m = sc();
while(m--) {
cin >> s[++cnt];
int x = sc();
insert(x, cnt);
}
m = sc();
while(m--) {
int x = sc();
query(x);
}
return 0;
}