st+dfs序求lca

st+dfs序求lca

ll dfn[N][2], id[N << 1], s, n, m, tot;
vector<ll> g[N];
void dfs(ll u, ll fa) {
    dfn[u][0] = dfn[u][1] = ++tot;
    id[tot] = u;
    for (auto to : g[u]) {
        if (to != fa) {
            dfs(to, u);
            dfn[u][1] = ++tot;
            id[tot] = u;
        }
    }
}

class ST {
    static ll lg[N];
    ll n;
    function<ll(ll, ll)> cmp;
    vector<vector<ll>> table;
public:
    ST(ll* arr, ll _n, function<ll(ll, ll)>_cmp = [](ll a, ll b) {return a < b ? a : b; })
        : n(_n), cmp(_cmp)
    {
        if (!lg[0]) {
            lg[0] = -1;
            rep(i, 1, N - 1) {
                lg[i] = lg[i / 2] + 1;
            }
        }
        table = vector<vector<ll>>(lg[n] + 1, vector<ll>(n + 1));
        rep(i, 1, n) {
            table[0][i] = arr[i];
        }
        rep(i, 1, lg[n]) {
            table[0][i] = arr[i];
            for (ll j = 1;j + (1ll << i) - 1 <= n ; j++) {
                table[i][j] = cmp(table[i - 1][j], table[i - 1][j + (1<<(i-1))]);
            }
        }
    }
    ll qry(ll x, ll y) {
        ll t = lg[y - x + 1];
        return cmp(table[t][x], table[t][y - (1ll << t) + 1]);
    }
};
ll ST::lg[N];

 

posted @ 2022-01-07 14:58  DeaL57  阅读(47)  评论(0编辑  收藏  举报