Pagini recente » Cod sursa (job #124605) | Cod sursa (job #2459504) | Cod sursa (job #2376900) | Cod sursa (job #1491099) | Cod sursa (job #1283410)
//Deresu Roberto - FMI
//Re :)
#include<fstream>
#include<vector>
#define nx 100007
using namespace std;
int n,m,x,y,father;
struct lca
{
int father;
int height;
}a[nx];
vector<int>v[nx];
ifstream fin("lca.in");
ofstream fout("lca.out");
void dfs(int node, int height)
{
a[node].height = height;
for(int i=0;i<v[node].size();i++)
dfs(v[node][i], height+1);
}
int lca(int x,int y)
{
while(a[x].height > a[y].height) x = a[x].father;
while(a[y].height > a[x].height) y = a[y].father;
while(x != y)
{
x = a[x].father;
y = a[y].father;
}
return x;
}
int numar()
{
int i,nr;
char s[7];
i = 0;
nr = 0;
fin>>s;
while(s[i]) nr = nr*10+s[i]-'0', ++i;
return nr;
}
int main()
{
fin>>n>>m;
for(int i=2;i<=n;i++)
{
father = numar();
a[i].father = father;
v[father].push_back(i);
}
dfs(1,1);
for(int i=1;i<=m;i++)
{
x = numar();
y = numar();
while(a[x].height > a[y].height) x = a[x].father;
while(a[y].height > a[x].height) y = a[y].father;
while(x != y)
{
x = a[x].father;
y = a[y].father;
}
fout<<x<<"\n";
}
return 0;
}