求调,100分subtask全TLE
查看原帖
求调,100分subtask全TLE
737088
WUYUEZE楼主2024/8/6 19:05
#include<bits/stdc++.h>
using namespace std;
int n[1000010];
vector<int> u[1000010];
int m[1000010];
vector<int> w[1000010];
bool v[1000010];
int o[1000010];
void f(int x){
    for(int i=0;i<u[x].size();i++){
        if(!v[u[x][i]]){
            w[x].push_back(u[x][i]);
            v[u[x][i]]=1;
            f(u[x][i]);
        }
    }
}
int g(int x,int y){
   if(o[x]==o[y]){
       if(x==y){
           return x;
       }
       else{
           return g(x,m[y]);
       }
   }
   else if(o[x]<o[y]){
       return g(x,m[y]);
   }
   else{
       return g(m[x],y);
   }
}
void h(int x){
    for(int i=0;i<w[x].size();i++){
        o[w[x][i]]=o[x]+1;
        h(w[x][i]);
    }
}
int main(){
    int a,b,c;
    scanf("%d%d%d",&a,&b,&c);
    for(int i=1;i<a;i++){
        int x,y;
        scanf("%d%d",&x,&y);
        u[x].push_back(y);
        u[y].push_back(x);
    }
    v[c]=1;
    f(c);
    for(int i=1;i<=a;i++){
        for(int j=0;j<w[i].size();j++){
            m[w[i][j]]=i;
        }
    }
    h(c);
    while(b--){
        int x,y;
        scanf("%d%d",&x,&y);
        printf("%d\n",g(x,y));
    }
    return 0;
}
2024/8/6 19:05
加载中...