MnZn求助平衡树
查看原帖
MnZn求助平衡树
376161
Phartial啊?楼主2021/10/30 15:13

rt,写的FHQ Treap

只拿了36分

#include <iostream>
#include <random>

using namespace std;
using LL = long long;

const int kN = 1e5 + 1;

namespace Random {
random_device rd;
mt19937 rnd(rd());
mt19937_64 rnd_64(rd());

int rand(int l, int r) {
  return uniform_int_distribution<int>(l, r)(rnd);
}

long long rand(long long l, long long r) {
  return uniform_int_distribution<long long>(l, r)(rnd_64);
}

double rand(double l, double r) {
  return uniform_real_distribution<double>(l, r)(rnd);
}
}  // namespace Random

namespace Treap {
struct FHQtreap {
  struct E {
    int v, p, l, r, s;
  } e[kN];

  int c, r;

  void Update(int x) {
    if (x) {
      e[x].s = e[e[x].l].s + e[e[x].r].s + 1;
    }
  }

  int Create(int v) {
    int x = ++c;
    e[x] = {v, (int)Random::rnd(), 0, 0, 1};
    return x;
  }

  void Split(int x, int v, int &rx, int &ry) {
    if (x) {
      if (v < e[x].v) {
        ry = x, Split(e[x].l, v, rx, e[x].l);
      } else {
        rx = x, Split(e[x].r, v, e[x].r, ry);
      }
      Update(x);
    } else {
      rx = ry = 0;
      return;
    }
  }

  int Merge(int x, int y) {
    if (!x || !y) {
      return x ^ y;
    }
    if (e[x].p > e[y].p) {
      e[x].r = Merge(e[x].r, y), Update(x);
      return x;
    } else {
      e[y].l = Merge(x, e[y].l), Update(y);
      return y;
    }
  }

  void Insert(int v) {
    int x, y;
    Split(r, v - 1, x, y), r = Merge(Merge(x, Create(v)), y);
  }

  void Delete(int v) {
    int x, y, z;
    Split(r, v, x, z), Split(x, v - 1, x, y), y && (y = Merge(e[y].l, e[y].r)), r = Merge(Merge(x, y), z);
  }

  int Rank(int v) {
    int x, y, s;
    Split(r, v - 1, x, y), s = e[x].s + 1, r = Merge(x, y);
    return s;
  }

  int At(int v) {
    int x = r;
    for (int _s; (_s = e[e[x].l].s + 1) != v; v -= (_s < v) * _s, x = (_s > v ? e[x].l : e[x].r)) {
    }
    return e[x].v;
  }

  int Pre(int v) {
    int x, y, s, i;
    for (Split(r, v - 1, x, y), i = x; s = e[i].v, e[i].r; i = e[i].r) {
    }
    return r = Merge(x, y), s;
  }

  int Next(int v) {
    int x, y, s, i;
    for (Split(r, v, x, y), i = y; s = e[i].v, e[i].l; i = e[i].l) {
    }
    return r = Merge(x, y), s;
  }
};
}  // namespace Treap

int q, o, x;
Treap::FHQtreap t;

int main() {
  // freopen("P3369_3.in", "r", stdin);
  // freopen("P3369.out", "w", stdout);
  cin >> q;
  for (int i = 1; i <= q; ++i) {
    cin >> o >> x;
    if (o == 1) {
      t.Insert(x);
    } else if (o == 2) {
      t.Delete(x);
    } else if (o == 3) {
      cout << t.Rank(x) << endl;
    } else if (o == 4) {
      cout << t.At(x) << endl;
    } else if (o == 5) {
      cout << t.Pre(x) << endl;
    } else {
      cout << t.Next(x) << endl;
    }
  }
  return 0;
}
2021/10/30 15:13
加载中...