Cod sursa(job #1170172)
Utilizator | Data | 12 aprilie 2014 19:57:39 | |
---|---|---|---|
Problema | Lowest Common Ancestor | Scor | 60 |
Compilator | cpp | Status | done |
Runda | Arhiva educationala | Marime | 1.57 kb |
#include<fstream>
#include<vector>
using namespace std;
ifstream fin("lca.in");
ofstream fout("lca.out");
struct nod
{
int tata,indice;
};
int n,m,a[100005],x,y;
vector<nod>H[7013];
inline void Citire()
{
int i;
fin>>n>>m;
for (i=2;i<=n;i++)
fin>>a[i];
}
inline void Rezolva()
{
int i,nr,poz,len,test,taticu;
nod k;
while (m--)
{
fin>>x>>y;
while (x)
{
poz=x%7013;
test=0;
len=H[poz].size();
for (i=0;i<len;i++)
if (H[poz][i].tata==x)
{
test=1;
H[poz][i].indice=m;
}
if (!test)
{
k.tata=x;
k.indice=m;
H[poz].push_back(k);
}
x=a[x];
}
nr=0;test=0;
while (y && !test)
{
poz=y%7013;
test=0;
len=H[poz].size();
for (i=0;i<len && !test;i++)
if (H[poz][i].tata==y && H[poz][i].indice==m)
{test=1;taticu=H[poz][i].tata;}
y=a[y];
}
fout<<taticu<<"\n";
}
}
int main()
{
Citire();
Rezolva();
return 0;
}