为啥dfs(s, 0)会wa, dfs(s, 1)就会过
查看原帖
为啥dfs(s, 0)会wa, dfs(s, 1)就会过
476449
lizipan楼主2021/9/7 19:32
#include<bits/stdc++.h>
typedef long long ll;
//======================================
const int maxn = 1e6 + 30;
int n, m, s, fa[maxn], nx[maxn], to[maxn], dep[maxn], cnt = 0, ft[maxn], hv[maxn][60];
void add (int x, int y){
    nx[++cnt] = ft[x];
    ft[x] = cnt;
    to[cnt] = y;
}
void dfs(int x, int d){
    dep[x] = d;
    hv[x][0] = fa[x];
    for (int i = 1; (1 << i) <= dep[x]; i++){
        hv[x][i] = hv[hv[x][i - 1]][i - 1];
    }
    for (int i = ft[x]; i; i = nx[i]){
        if (fa[x] != to[i]){
            fa[to[i]] = x;
            dfs(to[i], d + 1);
        }
    }
}
int jump(int x, int y){
    if (dep[x] > dep[y]) std::swap(x, y);
    for (int i = (int)log2(dep[y] - dep[x]); i >= 0; i--){
        if (dep[hv[y][i]] >= dep[x]){
            if (hv[y][i] == x) return x;
            y = hv[y][i];
        }
    }
    if (x == y) return x;
    for (int i = (int) log2(dep[x]); i >= 0; i--){
        if ((1 << i) <= dep[x]){
            if (hv[x][i] != hv[y][i]){
                x = hv[x][i], y = hv[y][i];
            }
        }
    }
    return fa[x];
}

int main(int argc, char const *argv[])
{
#ifdef LOCAL
    freopen("in.in", "r", stdin);
    freopen("out.out", "w", stdout);
#endif
    clock_t c1 = clock();
    //======================================
    scanf("%d%d%d", &n, &m, &s);
    int x, y;
    for (int i = 1; i < n; i++){
        scanf("%d%d", &x, &y);
        add(x, y);
        add(y, x);
    }
    dfs(s, 1);
    for (int i = 0; i < m; i++){
        scanf("%d%d", &x, &y);
        printf("%d\n", jump(x, y));
    }
    //======================================
    std::cerr << "Time:" << clock() - c1 << "ms" << std::endl;
    return 0;
}
2021/9/7 19:32
加载中...