Pagini recente » Cod sursa (job #2209976) | Cod sursa (job #328566) | Cod sursa (job #571815) | Cod sursa (job #2453863) | Cod sursa (job #1283418)
//Deresu Roberto - FMI
//Re :)
#include<fstream>
#include<vector>
#define nx 100007
using namespace std;
int n,m;
char s[nx*7];
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 main()
{
fin>>n>>m;
fin.getline(s,sizeof(s));
fin.getline(s,sizeof(s));
int j = 0;
for(int i=2;i<=n;i++)
{
int father = 0;
while(s[j] && s[j]!= ' ') father = father*10+s[j]-'0', ++j;
++j;
a[i].father = father;
v[father].push_back(i);
}
dfs(1,1);
for(int i=1;i<=m;i++)
{
int x, y, j;
fin.getline(s,sizeof(s));
x = 0;
y = 0;
j = 0;
while(s[j] && s[j]!= ' ') x = x*10+s[j]-'0', ++j;
++j;
while(s[j] && s[j]!= ' ') y = y*10+s[j]-'0', ++j;
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;
}