Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- #define forn(i, n) for(int i = 0; i < int(n); ++i)
- using namespace std;
- using ll = long long;
- mt19937 rng(111111);
- struct treap {
- treap* l = nullptr;
- treap* r = nullptr;
- treap* p = nullptr;
- int key;
- ll pr;
- int sz;
- treap(int key) : key(key), pr(rng()), sz(1) {}
- };
- treap* arr[300300];
- int gs(treap* v) {
- return v ? v->sz : 0;
- }
- int getKey(treap* v) {
- return v ? v->key : 0;
- }
- bool isLeft(treap* v, int le) {
- return getKey(v->l) == le;
- }
- void rs(treap* v) {
- if (!v) return;
- v->sz = 1 + gs(v->l) + gs(v->r);
- v->p = nullptr;
- if (v->l) v->l->p = v;
- if (v->r) v->r->p = v;
- }
- treap* merge(treap* l, treap* r) {
- if (!l || !r) {
- rs(l), rs(r);
- return l ? l : r;
- }
- if (l->pr > r->pr) {
- l->r = merge(l->r, r);
- rs(l);
- return l;
- } else {
- r->l = merge(l, r->l);
- rs(r);
- return r;
- }
- }
- pair<treap*, treap*> split(treap* v, int key) {
- if (!v) return {v, v};
- if (gs(v->l) + 1 <= key) {
- auto [l, r] = split(v->r, key - 1 - gs(v->l));
- v->r = l;
- rs(v);
- rs(r);
- return {v, r};
- } else {
- auto [l, r] = split(v->l, key);
- v->l = r;
- rs(v);
- rs(l);
- return {l, v};
- }
- }
- int ind(int cur) {
- int ans = gs(arr[cur]->l) + 1;
- while (arr[cur]->p) {
- int p = getKey(arr[cur]->p);
- if (!isLeft(arr[p], cur)) {
- ans += gs(arr[p]->l) + 1;
- }
- cur = p;
- }
- return ans;
- }
- tuple<treap*, treap*, treap*> fff(treap* v, int k) {
- auto [l, x] = split(v, k - 1);
- auto [w, r] = split(x, 1);
- return {l, w, r};
- }
- int main() {
- ios_base::sync_with_stdio(false);
- cin.tie(nullptr);
- cout.tie(nullptr);
- int n, m, t;
- cin >> n >> m >> t;
- if (t == 2) {
- arr[0] = nullptr;
- treap* root = arr[0];
- for (int i = 1; i <= m; i++) {
- arr[i] = new treap(i);
- root = merge(root, arr[i]);
- }
- for (int i = 0; i < n; i++) {
- int k;
- cin >> k;
- auto [l, v, r] = fff(root, k);
- cout << v->key << ' ';
- root = merge(v, merge(l, r));
- }
- return 0;
- } else {
- arr[0] = nullptr;
- treap* root = arr[0];
- for (int i = 1; i <= m; i++) {
- arr[i] = new treap(i);
- root = merge(root, arr[i]);
- }
- for (int i = 0; i < n; i++) {
- int x;
- cin >> x;
- int index = ind(x);
- int jndex = ind(index);
- if (index == jndex) {
- auto [L, V, R] = fff(root, index);
- root = merge(V, merge(L, R));
- rs(root);
- } else if (index < jndex) {
- auto [P, V, R] = fff(root, jndex);
- auto [L, X, MID] = fff(P, index);
- root = merge(X, merge(L, merge(V, merge(MID, R))));
- rs(root);
- } else {
- auto [P, X, R] = fff(root, index);
- auto [L, V, MID] = fff(P, jndex);
- root = merge(X, merge(L, merge(V, merge(MID, R))));
- rs(root);
- }
- cout << index << ' ';
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement