Pagini recente » Cod sursa (job #1500548) | Cod sursa (job #1617353) | Cod sursa (job #2235485) | Cod sursa (job #584989) | Cod sursa (job #916948)
Cod sursa(job #916948)
#include<fstream>
#include<vector>
using namespace std;
ifstream f("lca.in");
ofstream g("lca.out");
int N,M;
struct nod{
int h,t;
};
vector<nod> V;
int lca(int x,int y){
while(1<2)
if(V[x].h==V[y].h)
if(V[x].t==V[y].t)
return V[x].t;
else
x=V[x].t,y=V[y].t;
else{
if(V[x].t==y) return y;
if(V[y].t==x) return x;
if(V[x].h<V[y].h){V[y].h--;continue;}
if(V[y].h<V[x].h){V[x].h--;continue;}
}
}
int main(){
int t,x,y;
f>>N>>M;
V.resize(N+1);
for(int i=2;i<=N;i++){
f>>t;
V[i].t=t;
V[i].h=V[t].h+1;
}
for(int i=0;i<M;i++){
f>>x>>y;
g<<lca(x,y)<<'\n';
}
return 0;
}