Pagini recente » Cod sursa (job #266011) | Cod sursa (job #638959)
Cod sursa(job #638959)
using namespace std;
#include <set>
#include <map>
#include <list>
#include <deque>
#include <stack>
#include <queue>
#include <cmath>
#include <ctime>
#include <cctype>
#include <cstdio>
#include <vector>
#include <string>
#include <bitset>
#include <utility>
#include <iomanip>
#include <fstream>
#include <cstring>
#include <sstream>
#include <iostream>
#include <algorithm>
#include <functional>
#define oo (1<<30)
#define f first
#define s second
#define II inline
#define db double
#define ll long long
#define pb push_back
#define mp make_pair
#define Size(V) ((ll)(V.size()))
#define all(V) (V).begin() , (V).end()
#define CC(V) memset((V),0,sizeof((V)))
#define CP(A,B) memcpy((A),(B),sizeof((B)))
#define FOR(i,a,b) for(int (i)=(a);(i)<=(b);++(i))
#define REP(i, N) for (int (i)=0;(i)<(int)(N);++(i))
#define FORit(it, x) for (__typeof((x).begin()) it = (x).begin(); it != (x).end(); ++it)
#define printll(x) printf("%lld",(x))
#define printsp() printf(" ")
#define newline() printf("\n")
#define readll(x) scanf("%lld",&(x))
#define debugll(x) fprintf(stderr,"%lld\n",(x))
#define N_MAX (1<<18)
typedef vector<int> VI;
typedef pair<int,int> pi;
typedef pair<short int,short int> ps;
typedef vector<string> VS;
template<class T> string toString(T n) {ostringstream ost;ost<<n;ost.flush();return ost.str();}
int N,M;
int Poz[N_MAX],Q[N_MAX],H[N_MAX],T[N_MAX];
int Pow2[N_MAX],Rmq[19][N_MAX]; //twice the size
vector<VI> A(N_MAX);
bool viz[N_MAX];
ifstream fin ("lca.in");
ofstream fout ("lca.out");
II void scan()
{
fin >> N >> M;
FOR(i,2,N)
{
fin >> T[i];
A[ T[i] ].pb(i);
}
}
II void DF(int nod)
{
viz[nod] = true;
Q[++Q[0]] = nod;
Poz[nod] = Q[0];
FORit(it,A[nod])
if(!viz[*it])
{
H[*it] = H[nod] + 1;
DF(*it);
Q[++Q[0]] = nod;
}
}
II int query_rmq(int x,int y)
{
if(x > y) swap(x,y);
int step = Pow2[y - x];
if(H[ Rmq[step][x] ] < H[ Rmq[step][y - (1<<step) + 1 ] ])
return Rmq[step][x];
return Rmq[step][y - (1<<step) + 1];
}
II void solve()
{
DF(1);
Pow2[0] = 0;
Pow2[1] = 0;
FOR(i,2,Q[0])
Pow2[i] = Pow2[i / 2] + 1;
FOR(i,1,Q[0])
Rmq[0][i] = Q[i];
FOR(step,1,17)
FOR(i,1,Q[0])
{
int j = min(Q[0],i + (1<<(step - 1)) );
if(H[ Rmq[step - 1][i] ] < H[ Rmq[step - 1][j] ])
Rmq[step][i] = Rmq[step - 1][i];
else
Rmq[step][i] = Rmq[step - 1][j];
}
int x,y;
FOR(i,1,M)
{
fin >> x >> y;
fout << query_rmq(Poz[x],Poz[y]);
}
}
int main()
{
scan();
solve();
return 0;
}