离线 Tarjan 算法

#include <bits/stdc++.h>

using namespace std;
using ll = long long;
using p = pair<int, int>;
const int maxn(5e5 + 10);
const int maxm(1e6 + 10);
int ecnt, qcnt;
bool vis[maxn];
int ehead[maxn], qhead[maxm];
int pre[maxn], ans[maxm];

struct edge {
    int to, nxt;
} edges[maxm];

struct que {
    int id, to, nxt;
} ques[maxm];

template<typename T = int>
inline const T read()
{
    T x = 0, f = 1;
    char ch = getchar();
    while (ch < '0' || ch > '9') {
        if (ch == '-') f = -1;
        ch = getchar();
    }
    while (ch >= '0' && ch <= '9') {
        x = (x << 3) + (x << 1) + ch - '0';
        ch = getchar();
    }
    return x * f;
}

template<typename T>
inline void write(T x, bool ln)
{
    if (x < 0) {
        putchar('-');
        x = -x;
    }
    if (x > 9) write(x / 10, false);
    putchar(x % 10 + '0');
    if (ln) putchar(10);
}

void addEdge(int u, int v)
{
    edges[ecnt].to = v;
    edges[ecnt].nxt = ehead[u];
    ehead[u] = ecnt++;
}

void addQue(int id, int u, int v)
{
    ques[qcnt].id = id;
    ques[qcnt].to = v;
    ques[qcnt].nxt = qhead[u];
    qhead[u] = qcnt++;
}

int Find(int x)
{
    return pre[x] == x ? x : pre[x] = Find(pre[x]);
}

void Union(int u, int v)
{
    pre[Find(v)] = Find(u);
}

void dfs(int cur, int pre)
{
    vis[cur] = true;
    for (int i = ehead[cur]; compl i; i = edges[i].nxt) {
        int nxt = edges[i].to;
        if (nxt not_eq pre) {
            dfs(nxt, cur);
        }
    }
    for (int i = qhead[cur]; compl i; i = ques[i].nxt) {
        int id = ques[i].id, nxt = ques[i].to;
        if (vis[nxt]) {
            ans[id] = Find(nxt);
        }
    }
    Union(pre, cur);
}

void tarjan(int tot, int root)
{
    for (int i = 1; i <= tot; ++i) {
        pre[i] = i;
    }
    dfs(root, 0);
}

int main()
{
#ifdef ONLINE_JUDGE
#else
    freopen("input.txt", "r", stdin);
#endif
    ios::sync_with_stdio(false);
    memset(ehead, -1, sizeof ehead);
    memset(qhead, -1, sizeof qhead);
    int n = read(), m = read(), s = read();
    for (int i = 0; i < n - 1; ++i) {
        int u = read(), v = read();
        addEdge(u, v);
        addEdge(v, u);
    }
    for (int i = 0; i < m; ++i) {
        int u = read(), v = read();
        addQue(i, u, v);
        addQue(i, v, u);
    }
    tarjan(n, s);
    for (int i = 0; i < m; ++i) {
        write(ans[i], true);
    }
    return 0;
}

最后更新于