不加输入输出优化可以过吗(
查看原帖
不加输入输出优化可以过吗(
231800
Veranda楼主2022/11/5 00:18

仅问下是算法问题吗,为啥加上优化输入输出才能过(

#include <iostream>
#include <algorithm>
#include <cstring>
#include <vector>
#include <queue>
#include <cstdio>

using namespace std;

const int N = 500010,M = N * 2;

int n,T;
int root;
int h[N],e[M],ne[M],idx;
int depth[N];
bool vis[N];
int fa[N][20];
queue<int> q;

void add(int a,int b){
    e[idx] = b,ne[idx] = h[a],h[a] = idx ++;
}

void bfs(int root){
    memset(depth,0x3f,sizeof depth);
    q.push(root);
    depth[0] = 0;
    depth[root] = 1;
    
    while(!q.empty()){
        int t = q.front();
        q.pop();
        for(int i = h[t];~i;i = ne[i]){
            int j = e[i];
            if(depth[j] > depth[t] + 1){
                depth[j] = depth[t] + 1;
                q.push(j);
                fa[j][0] = t;
                for(int k = 1;k <= 19;k ++){
                    fa[j][k] = fa[fa[j][k - 1]][k - 1];
                }
            }
        }
    }
}

int lca(int x,int y){
    if(depth[x] < depth[y]) swap(x,y);
    
    for(int k = 19;k >= 0;k --){
        if(depth[fa[x][k]] >= depth[y]) x = fa[x][k];
    }
    
    if(x == y) return x;
    
    for(int k = 19;k >= 0;k --){
        if(fa[x][k] != fa[y][k]) x = fa[x][k],y = fa[y][k];
    }
    
    return fa[x][0];
}

int main(){
    std::ios::sync_with_stdio(false);

    memset(h,-1,sizeof(h));
    
    cin >> n >> T >> root;
    for(int i = 1;i < n;i ++){
        int a,b;
        cin >> a >> b;
        //if(b == -1) root = a;
        add(a,b),add(b,a);
    }
    
    bfs(root);
    
    //cin >> T;
    
    while(T --){
        int a,b;
        cin >> a >> b;
        int ans = lca(a,b);
        cout << ans << endl;
    }
    
    
    
}
2022/11/5 00:18
加载中...