倍增LCA只有70分,萌新求助
查看原帖
倍增LCA只有70分,萌新求助
235566
_agKc_楼主2023/4/12 20:53

只有70分,sub0后面的WA了,sub1后面的TLE了,自己找半天没找出问题,大佬们能不能帮蒟蒻看看

#include <bits/stdc++.h>
#include <iostream>
#include <cstdio>
#define int long long

using namespace std;
vector<int> to[500005];
int dep[500005], fa[500000][30];
void dfs(int x){
    for(int i=1;i<log2(dep[x]);i++){
        fa[x][i]=fa[fa[x][i-1]][i-1];
    }
    for(int v:to[x]){
        if(v==fa[x][0])continue;
        dep[v]=dep[x]+1;
        fa[v][0]=x;
        dfs(v);
    }
}
int LCA(int x,int y){
    if(dep[x]!=dep[y]){
        // cout<<"233"<<endl;
        if (dep[x] < dep[y])
            swap(x, y);
        for (int i = log2(dep[x]-dep[y]); i >= 0; i--)
        {
            if(dep[fa[x][i]]>=dep[y]){
                x=fa[x][i];
            }
            if(x==y)return x;
        }

    }
    for(int i=log2(dep[x]);i>=0;i--){
        if(fa[x][i]!=fa[y][i]){
            x=fa[x][i];
            y=fa[y][i];
            // cout<<"jump"<<endl;
        }
    }
    return fa[x][0];
}
signed main()
{
    int n, m, s;
    cin >> n >> m >> s;
    for (int i = 1, x, y; i < n; i++)
    {
        scanf("%d%d",&x,&y);
        to[x].push_back(y);
        to[y].push_back(x);
    }
    dep[s]=1;
    dfs(s);

    for(int i=1,x,y;i<=m;i++){
        scanf("%d%d", &x, &y);
        cout<<LCA(x,y)<<endl;
    }

    return 0;
}
2023/4/12 20:53
加载中...