Pagini recente » Cod sursa (job #678133) | Cod sursa (job #3237609) | Cod sursa (job #952864) | Cod sursa (job #2235577) | Cod sursa (job #1548511)
#include <iostream>
#include <fstream>
#include <cmath>
#include <vector>
using namespace std;
const int nmax = 1e5+5;
vector <int> g[nmax];
int p[nmax], h[nmax], t[nmax];
int lca(int x, int y)
{
while(p[x]!=p[y])
{
if(h[x] > h[y]) x=p[x];
else y=p[y];
}
while(x!=y)
{
if(h[x] > h[y]) x=t[x];
else y=t[y];
}
return x;
}
void dfs(int dad, int x)
{
if(h[dad] < x) p[dad] = 1;
else if(h[dad]%x==0) p[dad]=t[dad];
else p[dad]=p[t[dad]];
int i, son;
for(i=0; i<g[dad].size(); i++)
{
son=g[dad][i];
dfs(son, x);
}
}
int main()
{
ifstream fin("lca.in");
ofstream fout("lca.out");
ios_base::sync_with_stdio(false);
int n, m, x, y, hmax = 0, i;
fin >> n >> m;
for(i=2; i<=n; i++)
{
fin >> t[i];
g[t[i]].push_back(i);
h[i] = h[t[i]] + 1;
hmax=max(hmax, h[i]);
}
dfs(1, sqrt(hmax));
for(i=1; i<=m; i++)
{
fin >> x >> y;
fout << lca(x, y) << "\n";
}
fin.close();
fout.close();
return 0;
}