大佬们,TLE8和9了,还能怎么优化?
查看原帖
大佬们,TLE8和9了,还能怎么优化?
1229738
SparkingDaydream楼主2024/11/21 22:29

题解里面对三个点两两的lca做了分类讨论判断,推出来一些性质,但是我比较懒,直接循环,但是,怎么这还能T的,我找完LCA后循环的次数只有3啊!!!! 求调!!!

#include<bits/stdc++.h>
#define int long long
#define double long double
using namespace std;
const int N=5e5+10;
const int inf=0x3f3f3f3f3f;
inline int read(){
    int 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*10+ch-'0',ch=getchar();
    return x*f;
}


vector<int>e[N];
int dep[N];
int fa[N][22];
void solve(){
    int n=read(),m=read();
    for(int i=1;i<=n-1;i++){
        int a=read(),b=read();
        e[a].push_back(b);
        e[b].push_back(a);
    }

    vector<int>dep(n+1,0);
    auto dfs=[&](auto&&self,int x,int father)->void{
        dep[x]=dep[father]+1;
        fa[x][0]=father;
        for(int i=1;i<=19;i++)
            fa[x][i]=fa[fa[x][i-1]][i-1];
        for(auto y:e[x])
            if(y!=father) self(self,y,x);
    };
    dep[0]=-1;
    dfs(dfs,1,0);
    auto lca=[&](int x,int y)->int{
        if(dep[x]<dep[y]) swap(x,y);
        for(int i=19;i>=0;i--)
            if(dep[fa[x][i]]>=dep[y]) x=fa[x][i];
        if(x==y) return x;
        for(int i=19;i>=0;i--)
            if(fa[x][i]!=fa[y][i])
                x=fa[x][i],y=fa[y][i];
        return fa[x][0];
    };

    for(int i=1;i<=m;i++){
        int a=read(),b=read(),c=read();
        if(a==b&&b==c){
            cout<<a<<" "<<0<<endl;
        }else{
            int rt[4];
            rt[1]=lca(a,b),rt[2]=lca(a,c),rt[3]=lca(b,c);
            int Min=inf,ans;
            int temp=dep[a]+dep[b]+dep[c];
            for(int i=1;i<=3;i++){
                int x=rt[i];
                int sum=temp+3*dep[x]-2*dep[lca(a,x)]-2*dep[lca(b,x)]-2*dep[lca(c,x)];
                if(sum<Min){
                    Min=sum;
                    ans=rt[i];
                }
            }
            cout<<ans<<" "<<Min<<endl;
        }
    }
    
}
signed main(){
    solve();
    return 0;
}
2024/11/21 22:29
加载中...