写在前头
本篇题解不讲Splay的原理,只给代码和细节讲解,保证代码不会被hack掉,且及其简短。如果你是洛谷88分#12 TLE了的倒霉蛋,那么恭喜你,请直接跳转到注释版代码第63行。
来吧!
标准代码
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 1, INF = 0x3f3f3f3f;
int n;
struct Splay {
int tot, root;
int ch [N + 3] [2], fa [N + 3];
int cnt [N + 3], siz [N + 3], val [N + 3];
void Begin () {
Insert (-INF); Insert (INF);}
inline void rotate (int x) {
int y = fa [x], z = fa [y];
bool d1 = cald (y), d2 = cald (x);
int s = ch [x] [!d2];
fa [s] = y; fa [y] = x; fa [x] = z;
ch [z] [d1] = x; ch [x] [!d2] = y; ch [y] [d2] = s;
push_up (y); push_up (x);
}
void splay (int x, int tar = 0) {
while (fa [x] != tar) {
if (fa [fa [x]] != tar)
rotate (cald (x) == cald (fa [x]) ? fa [x] : x);
rotate (x);
}
if (!tar) root = x;
}
int get_pre (int k) {
int pre, y = 0;
for (int x = root; x; y = x, x = ch [x] [k > val [x]])
if (val [x] < k) pre = x;
splay (y);
return pre;
}
int get_nxt (int k) {
int nxt, y = 0;
for (int x = root; x; y = x, x = ch [x] [k >= val [x]])
if (val [x] > k) nxt = x;
splay (y);
return nxt;
}
int Get_Pre (int k) {
return val [get_pre (k)];}
int Get_Nxt (int k) {
return val [get_nxt