CF2135F To the Infinity

· · 题解

这里是验题人发现的一个能过的朴素暴力,而且跑得比 std 快。考虑到能这么想的应该是神人,而且完全卡不掉,我们在比赛开始前仍无法想出可行且现实的补救方案。看上去这个暴力的存在并没有影响到比赛,但是还是给大家磕头了。

前半部分还是一样,对整个树拓扑排序,然后需要维护一个字典序比较状物。考虑人类智慧做法:对于每个节点直接暴力用 vector 维护这个点指数上的所有 rk,然后把 rk 相同的全压缩到一起。比较插入啥的全部暴力用 vector 做,然后你发现你过了?

复杂度我只会分析一点。你考虑你要卡死这东西大概得搞两条链,链上要一半空一半挂满本质不同的二叉树。考虑到大小为 n 的二叉树只有 O(2^n) 种,你只能搞出 O(\frac{n}{\log n}) 个。所以总复杂度是 O(\frac{n^2}{\log n}) 带一个逆天的 \frac1{32} 常数。这个神秘的 \frac1{32} 甚至是所有朴素暴力自带的,导致即使不压缩 rk 在 n=2\times10^5 的情况下我都卡不掉 O(n^2) 暴力。数据里面八个针对这东西的 hack 点他表现全都比 std 好,因为这同时也是 std 最坏情况。火大。

挂个代码在这了。赛前三天卡这东西卡到脑溢血了,想吐。

#include <bits/stdc++.h>

using namespace std;

typedef unsigned long long ull;

const int MAXN = 4e5 + 10;

ull A = mt19937_64(time(0))();

inline ull shift(ull x) {
    return x ^= A, x ^= x << 13, x ^= x >> 7, x ^= x << 11, x ^= A;
}

int n, l[MAXN], r[MAXN], fa[MAXN], d[MAXN];

vector<pair<int, int>> p[MAXN]; ull h[MAXN];

int rk[MAXN], tot, lst;

struct cmp {
    bool operator () (int x, int y) { return h[x] == h[y] ? x > y : p[x] > p[y]; }
}; priority_queue<int, vector<int>, cmp> q;

inline 
void upd(int u) {
    h[u] = h[l[u]] + shift(h[r[u]]), p[u].swap(p[l[u]]);
    int k = lower_bound(p[u].begin(), p[u].end(), make_pair(rk[r[u]], 1e9), greater<pair<int, int>>()) - p[u].begin();
    if (k < p[u].size() && p[u][k].first == rk[r[u]]) p[u][k].second++;
    else p[u].insert(p[u].begin() + k, make_pair(rk[r[u]], 1));
}

int T;

int main() {
    for (scanf("%d", &T); T--; ) {
        scanf("%d", &n), lst = tot = 0;
        for (int i = 1; i <= n; i++) p[i].clear();
        for (int i = 1; i <= n; i++) {
            scanf("%d%d", &l[i], &r[i]);
            d[i] = (l[i] && r[i] ? 2 : 0), fa[l[i]] = fa[r[i]] = i;
        }
        for (int i = 1; i <= n; i++) if (!d[i]) h[i] = 1, q.emplace(i);
        for (int u; !q.empty(); ) {
            printf("%d ", u = q.top()), q.pop();
            if (h[u] != h[lst]) tot++; lst = u, rk[u] = tot;
            if (!--d[fa[u]]) upd(fa[u]), q.push(fa[u]);
        }
        puts("");
    }
}

如果有老哥卡掉了这个暴力可以戳我一下。