树剖LCA最后一个点TLE
查看原帖
树剖LCA最后一个点TLE
566168
川寰boy楼主2025/8/2 15:20
#include <iostream>
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <string>
#include <map>
#include <vector>
#include <queue>
#include <stack>
#include <deque>
using namespace std;

// #define int long long
template <class T>
string toString(T x) { return to_string(x); }
string toString(const char *x) { return string(x); }
string toString(const string &x) { return x; }
template <class T>
string expand(const T &x) { return toString(x); }
template <class T, class... A>
string expand(const T &x, A... a) { return expand(x) + ", " + expand(a...); }
int read(){int type = 1, n = 0;char ch = getchar();while (ch < '0' || ch > '9'){if (ch == '-'){type = -1;}ch = getchar();}while (ch >= '0' && ch <= '9'){n = (n << 1) + (n << 3) + (ch ^ 48),ch = getchar();}return n * type;}
void write(int n){if (n < 0){putchar('-'), n = -n;}if (n < 10){return putchar(n + '0'), void();}return write(n / 10), putchar(n % 10 + '0'), void();}
void wt(int n, bool o = 1){write(n);if (!o){putchar(' ');}else{putchar('\n');}}

#define debug(a...) cerr << "[" << #a << "] = " << expand(a) << '\n'
#define fileio(x) (freopen(x".in", "r", stdin), freopen(x".out", "w", stdout))
#define rd read()
#define ptc putchar('\n')

const int N = 5e5 + 10;
const int MOD = 998244353;
const int INF = 0x7fffffff;
const int Fill = 0x3f3f3f3f;

int n, m, s;
int tot;
int fa[N], bel[N], sz[N], dep[N], dfn[N], prince[N];
vector <int> G[N];

void dfs1(int id, int from)
{
    sz[id] = G[id].size() - 1;
    int max_ = 0;
    for (int son : G[id])
    {
        if (son == from) continue;
        fa[son] = id;
        dep[son] = dep[id] + 1;
        dfs1(son, id);
        if (max_ <= sz[son])
        {
            max_ = sz[son];
            prince[id] = son;
        }
    }
    return ;
}

void dfs2(int id, int num)
{
    dfn[id] = ++tot;
    bel[id] = num;
    if (prince[id])
    {
        dfs2(prince[id], num);
    }
    for (int son : G[id])
    {
        if (son == fa[id]) continue;
        if (son == prince[id]) continue;
        ++num;
        dfs2(son, son);
    }
    return ;
}

int lca(int x, int y)
{
    while (bel[x] != bel[y])
    {
        if (dep[bel[x]] >= dep[bel[y]])
        {
            x = fa[bel[x]];
        }
        else
        {
            y = fa[bel[y]];
        }
        // debug(x,y);
    }
    return dep[x] < dep[y] ? x : y;
}

void solve()
{
    int i, j;
    n = rd, m = rd, s = rd;
    for (i = 1; i <= n - 1; i++)
    {
        int u = rd, v = rd;
        G[u].push_back(v);
        G[v].push_back(u);
    }
    dfs1(s, 0);
    dfs2(s, s);
    for (i = 1; i <= n; i++)
    {
        if (!bel[i]) bel[i] = i;
        // wt(bel[i], 0);
    }
    for (i = 1; i <= m; i++)
    {
        int x = rd, y = rd;
        wt(lca(x, y));
    }
}

signed main()
{
    int T;
    int i, j;
    T = 1;
    while (T--)
    {
        
        solve();
    }
    return 0;
}
2025/8/2 15:20
加载中...