原本可以A,再交就一直TLE。
#include<iostream>
#include<algorithm>
#include<cstring>
#include<climits>
#include<cmath>
#include<queue>
#include<vector>
#include<stack>
#include<tuple>
#include<unordered_map>
#include<map>
#include<unordered_set>
#include<set>
#define rep(i,a,b,c) for(int i=(a);i<=(b);i+=(c))
#define per(i,a,b,c) for(int i=(a);i>=(b);i-=(c))
#define ALL(a) (a).begin(),(a).end()
using namespace std;
using ll = long long;
const int INF = 0x3f3f3f3f;
const int N = 5e5 + 5;
const int K = 32;
vector<int> g[N];
int n, m, s;
int f[N][K + 5], depth[N];
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;
}
namespace LCA {
void dfs(int u, int fa) {
//cout << f[u][0] << " ----> " << u << endl;
f[u][0] = fa;
depth[u] = depth[fa] + 1;
rep(k, 1, K, 1) {
int mid = f[u][k - 1];
f[u][k] = f[mid][k - 1];
}
for (auto v : g[u]) {
if (depth[v] > depth[u] + 1) {
dfs(v, u);
}
}
}
int lca(int a, int b) {
if (depth[a] > depth[b]) swap(a, b);
per(k, K, 0, 1) {
int pb = f[b][k];
if (depth[pb] >= depth[a]) {
b = pb;
}
}
if (a == b) return a;
per(k, K, 0, 1) {
int pa = f[a][k], pb = f[b][k];
if (pb != pa) {
a = pa, b = pb;
}
}
return f[a][0];
}
void init() {
memset(f, 0, sizeof(f));
memset(depth, 0x3f, sizeof(depth));
depth[0] = 0;
LCA::dfs(s, 0);
}
}
int main() {
n = read();
m = read();
s = read();
rep(i, 1, n - 1, 1) {
int u = read(), v = read();
g[u].push_back(v);
g[v].push_back(u);
}
LCA::init();
//rep(u, 1, n, 1)cout << u << " -> " << f[u][0] << endl;
rep(i, 1, m, 1) {
int u = read(), v = read();
cout << LCA::lca(u, v) << endl;
}
return 0;
}
球条,谢谢