树链剖分TLE求调
查看原帖
树链剖分TLE求调
802557
pyiming楼主2024/4/4 19:03
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N=5e6;
// struct lca{
//     vector<int> *edge;
//     int *son,*d,*top,*fa;
//     int n;
//     lca(int n,vector<int> *edge):n(n),edge(edge){
//         son=new int[n+1];
//         for(int i=1;i<=n;i++){
//             son[i]=0;//初始化
//         }
//         d=new int[n+1];
//         top=new int[n+1];
//         fa=new int[n+1];
//     }
//     ~lca(){
//         delete[] son,d,top,fa;
//     }
//     int dfs1(int u,int f,int depth){
//         int sum=1;
//         int temp=0;
//         d[u]=depth;
//         fa[u]=f;
//         for(int v:edge[u]) if(v!=f){
//             int t=dfs1(v,u,depth+1);
//             if(t>temp){
//                 son[u]=v;
//             }
//             sum+=t;
//         }
//         return sum;
//     }
//     void dfs2(int u,int fa,int t){
//         top[u]=t;
//         if(son[u]!=0) dfs2(son[u],u,t);
//         for(int v:edge[u]) if(v!=fa&&v!=son[u]){
//             dfs2(v,u,v);
//         }
//     }
//     int find(int x,int y){
//         if(top[x]==top[y]) return d[x]<d[y]?x:y;
//         if(d[top[x]]<d[top[y]]) swap(x,y);
//         return find(fa[top[x]],y);
//     }
// };
vector<int> edge[N+1];
int d[N+1],fa[N+1];
int son[N+1],top[N+1];
int dfs1(int u,int f,int depth){
    int sum=1;
    int temp=0;
    d[u]=depth;
    fa[u]=f;
    for(int v:edge[u]) if(v!=f){
        int t=dfs1(v,u,depth+1);
        if(t>temp){
            son[u]=v;
        }
        sum+=t;
    }
    return sum;
}
void dfs2(int u,int fa,int t){
    top[u]=t;
    if(son[u]!=0) dfs2(son[u],u,t);
    for(int v:edge[u]) if(v!=fa&&v!=son[u]){
        dfs2(v,u,v);
    }
}
int find(int x,int y){
    while(top[x]!=top[y]){
        if(d[top[x]]<d[top[y]]) swap(x,y);
        x=fa[top[x]];
    }
    return d[x]<d[y]?x:y;
}
int main(){
    // freopen("data.in","r",stdin);
    cin.tie(0)->sync_with_stdio(0);
    int n,m,s;
    cin>>n>>m>>s;
    // edge=new vector<int>[n+1];
    for(int i=1;i<n;i++){
        int u,v;
        cin>>u>>v;
        edge[u].push_back(v);
        edge[v].push_back(u);
    }
    // lca *c;
    // c=new lca(n,edge);
    dfs1(s,0,1);
    dfs2(s,0,s);
    // delete[] edge;
    while(m--){
        int a,b;
        cin>>a>>b;
        cout<<find(a,b)<<endl;
    }
    return 0;
}
2024/4/4 19:03
加载中...