Pagini recente » Cod sursa (job #2619716) | Cod sursa (job #1374535) | Cod sursa (job #1843628) | Cod sursa (job #667361) | Cod sursa (job #2607305)
#include <fstream>
using namespace std;
ifstream in("lca.in");
ofstream out("lca.out");
const int L = 17, N = 100001, M = 2 * 100001;
int n, m, t[L][N], vf[M], urm[M], lst[M], nr, timp, ti[N], to[N];
void adauga(int x, int y)
{
vf[++nr] = y;
urm[nr] = lst[x];
lst[x] = nr;
}
void dfs(int x)
{
ti[x] = ++timp;
for(int p = lst[x]; p != 0; p = urm[p])
{
int y = vf[p];
if(ti[y] == 0)
dfs(y), t[0][y] = x;
}
to[x] = ++timp;
}
int lca(int x, int y)
{
int pas = L-1;
if(ti[x] <= ti[y] && to[y] <= to[x])
return x;
while(pas >= 0)
{
int s = t[pas][x];
if(s != 0 && (ti[s] > ti[y] || to[y] > to[s]))
{
x = s;
}
pas--;
}
return t[0][x];
}
int main()
{
in >> n >> m;
for(int i = 2, x; i <= n; i++)
{
in >> x;
adauga(x, i);
//adauga(i, x);
}
dfs(1);
for(int i = 1; i < L; i++)
{
for(int j = 1; j <= n; j++)
{
t[i][j] = t[i-1][t[i-1][j]];
}
}
for(int i = 1, x, y; i <= m; i++)
{
in >> x >> y;
out << lca(x, y) << "\n";
}
return 0;
}