Treap

· · 个人记录

//%std
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <algorithm>
#include <cmath>
#include <vector>
#include <queue>
#include <stack>
#include <set>
#include <map>
using namespace std;
#define lovelive long long
#define lc son[x][0]
#define rc son[x][1]
#define lowbit(x) (x & (-x))
const int N = 1e5 + 100;
void read(int &x)
{
  x = 0;
  char c = getchar();
  while (c < '0' || c > '9')
    c = getchar();
  while (c >= '0' && c <= '9')
  {
    x = x * 10 + c - 48;
    c = getchar();
  }
}
int son[N][2], siz[N], key[N], cnt[N], rnd[N], tot, root;
void update(int x)
{
  siz[x] = cnt[x] + siz[lc] + siz[rc];
}
void rotate(int &x, int k)
{
  int v = son[x][k ^ 1];
  son[x][k ^ 1] = son[v][k];
  son[v][k] = x;
  update(x);
  update(v);
  x = v;
}
void insert(int &x, int ky)
{
  if (!x)
  {
    x = ++tot;
    siz[x] = cnt[x] = 1;
    key[x] = ky;
    rnd[x] = rand();
    return;
  }
  if (key[x] == ky)
  {
    ++siz[x];
    ++cnt[x];
    return;
  }
  int d = ky > key[x];
  ++siz[x];
  insert(son[x][d], ky);
  if (rnd[son[x][d]] < rnd[x])
    rotate(x, d ^ 1);
}
bool remove(int &x, int ky)
{
  if (!x)
    return false;
  if (ky == key[x])
  {
    if (cnt[x] > 1)
    {
      --siz[x];
      --cnt[x];
      return true;
    }
    if (!lc || !rc)
    {
      x = lc ? lc : rc;
      return true;
    }
    if (rnd[lc] < rnd[rc])
      rotate(x, 1);
    else
      rotate(x, 0);
    return remove(x, ky);
  }
  int d = ky > key[x];
  if (!remove(son[x][d], ky))
    return false;
  --siz[x];
  return true;
}
int find_rnk(int ky)
{
  int x = root, rnk = 1;
  while (x)
  {
    if (ky > key[x])
      rnk += siz[lc] + cnt[x], x = rc;
    else
    {
      if (ky < key[x])
        x = lc;
      else
        return siz[lc] + rnk;
    }
  }
}
int find_key(int k)
{
  int x = root;
  while (x)
  {
    if (k <= siz[lc])
      x = lc;
    else
    {
      if (siz[lc] + cnt[x] < k)
        k -= siz[lc] + cnt[x], x = rc;
      else
        return key[x];
    }
  }
}
int find_pre(int ky)
{
  int pre, x = root;
  while (x)
  {
    if (key[x] < ky)
      pre = key[x], x = rc;
    else
      x = lc;
  }
  return pre;
}
int find_nxt(int ky)
{
  int nxt, x = root;
  while (x)
  {
    if (key[x] > ky)
      nxt = key[x], x = lc;
    else
      x = rc;
  }
  return nxt;
}
int main()
{
  freopen("testdata.in", "r", stdin);
  int n, m, opt, x, ct = 0;
  read(n);
  for (int i = 1; i <= n; i++)
  {
    read(opt);
    read(x);
    if (ct == 286)
      ct--, ct++;
    switch (opt)
    {
    case 1:
      insert(root, x);
      break;
    case 2:
      remove(root, x);
      break;
    case 3:
      cout << find_rnk(x) << "\n";
      ++ct;
      break;
    case 4:
      cout << find_key(x) << "\n";
      ++ct;
      break;
    case 5:
      cout << find_pre(x) << "\n";
      ++ct;
      break;
    case 6:
      cout << find_nxt(x) << "\n";
      ++ct;
      break;
    }
  }
  return 0;
}