CF38G Queue 题解 splay tree

题目链接:https://codeforces.com/contest/38/problem/G

题目大意:

有n个人依次排队,每个人都有两个属性值 a[i] 、c[i] ,a[i]是重要性值,数值越大越重要,c[i]是良心值。假如前i-1人已经排好队后,第i个人来排队,初始时他在队尾,如果他的a[i]大于排在他前面那位的重要性值,那么两人可以交换位置,每次交换良心值减1,直到他前面的人的重要性值大于a[i]或者良心值为0的时候(即最多交换c[i]次),问最终n个人的队列次序。

解题思路:

每个节点维护子树大小(节点个数)和最大值。然后就是简单地插入即可。

示例程序:

#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e5 + 5;

struct Node {
    int s[2], p, v;
    int sz, mx;
    Node() {}
    Node(int _v, int _p) { s[0] = s[1] = 0; v = _v; p = _p; sz = 1; mx = _v; }
} tr[maxn];
int root, idx;

void push_up(int x) {
    auto &u = tr[x], &l = tr[u.s[0]], &r = tr[u.s[1]];
    u.sz = l.sz + 1 + r.sz;
    u.mx = max({l.mx, u.v, r.mx});
}

void f_s(int p, int u, bool k) {
    tr[p].s[k] = u;
    tr[u].p = p;
}

void rot(int x) {
    int y = tr[x].p, z = tr[y].p;
    bool k = tr[y].s[1] == x;
    f_s(z, x, tr[z].s[1]==y);
    f_s(y, tr[x].s[k^1], k);
    f_s(x, y, k^1);
    push_up(y), push_up(x);
}

void splay(int x, int k) {
    while (tr[x].p != k) {
        int y = tr[x].p, z = tr[y].p;
        if (z != k)
            (tr[y].s[1]==x) ^ (tr[z].s[1]==y) ? rot(x) : rot(y);
        rot(x);
    }
    if (!k) root = x;
}

void ins(int v, int c) {
    int u = root, p = 0, k = 0;
    while (u) {
        p = u;
        k = (v < tr[tr[u].s[1]].mx || v < tr[u].v || c <= tr[tr[u].s[1]].sz);
        if (!k)
            c -= tr[tr[u].s[1]].sz + 1;
        u = tr[u].s[k];
    }
    tr[u = ++idx] = Node(v, p);
    if (p) tr[p].s[k] = u;
    splay(u, 0);
}

void output(int u) {
    if (!u) return;
    output(tr[u].s[0]);
    cout << u << " ";
    output(tr[u].s[1]);
}

void init() {
    tr[0] = Node(0, 0);
    tr[0].sz = 0;
}

int n;

int main() {
    init();
    cin >> n;
    for (int i = 0; i < n; i++) {
        int v, c;
        cin >> v >> c;
        ins(v, c);
    }
    output(root);
    return 0;
}
posted @ 2022-12-23 13:23  quanjun  阅读(28)  评论(0)    收藏  举报