主要问题是RE,返回值62097
Code:
#include <bits/stdc++.h>
using namespace std;
vector<int> V[500001];
int n, m;
int anc[500001][21];
int dep[500001] = {0};
int lg[500001] = {0};
void getlg()
{
for (int i = 1; i <= n; i++)
lg[i] = lg[i - 1] + (1 << lg[i - 1] == i);
for (int i = 1; i <= n; i++)
lg[i]--;
}
void init(int p, int father)
{
dep[p] = dep[father] + 1;
anc[p][0] = father;
for (int i = 1; i <= lg[dep[p]] + 1; i++)
anc[p][i] = anc[anc[p][i - 1]][i - 1];
for (int i = 0; i < V[p].size(); i++)
if (V[p][i] != father)
init(V[p][i], p);
}
int getLCA(int x, int y)
{
if (dep[x] < dep[y]) swap(x, y);
while (dep[x] > dep[y])
x = anc[x][lg[dep[x] - dep[y]]];
if (x == y) return x;
for (int i = lg[dep[x]]; i >= 0; i--)
if (anc[x][i] != anc[y][i])
x = anc[x][i], y = anc[y][i];
return anc[x][0];
}
int main()
{
ios::sync_with_stdio(0);
cin.tie(0), cout.tie(0);
cin >> n >> m;
for (int i = 1, u, v; i < n; i++)
{
cin >> u >> v;
V[u].push_back(v);
V[v].push_back(u);
}
getlg();
init(1, 1);
while (m--)
{
int x, y;
cin >> x >> y;
cout << getLCA(x, y) << endl;
}
return 0;
}
thx啦!!!