Pagini recente » Cod sursa (job #1165590) | Cod sursa (job #2158515) | Cod sursa (job #1815516) | Cod sursa (job #1482048) | Cod sursa (job #1173269)
#include <fstream>
#include <vector>
using namespace std;
const int NMax = 100010, TMax = 2000000;
int N, T;
int K;
int first[NMax], last[NMax];
vector <int> G[NMax];
int ancestor[17][NMax];
inline void DFS(const int &node, const int &father)
{
first[node] = ++ K;
ancestor[0][node] = father;
for (vector <int> :: iterator it = G[node].begin(); it != G[node].end(); ++ it)
DFS(*it, node);
last[node] = ++ K;
}
inline int GetLca(int x, const int y)
{
if (first[x] <= first[y] && last[y] <= last[x])
return x;
for (int i = 16; i >= 0; -- i)
if (ancestor[i][x] && ! (first[ancestor[i][x]] <= first[y] && last[y] <= last[ancestor[i][x]]))
x = ancestor[i][x];
return ancestor[0][x];
}
int main()
{
ifstream f("lca.in");
f >> N >> T;
for (int i = 2; i <= N; ++ i)
{
int father; f >> father;
G[father].push_back(i);
}
DFS(1, 0);
for (int i = 1; (1 << i) <= N; ++ i)
for (int j = 1; j <= N; ++ j)
ancestor[i][j] = ancestor[i-1][ancestor[i-1][j]];
ofstream g("lca.out");
for (int t = 1; t <= T; ++ t)
{
int x, y; f >> x >> y;
g << GetLca(x, y) << "\n";
}
g.close();
return 0;
}