Pagini recente » Cod sursa (job #2205670) | Cod sursa (job #1023377) | Cod sursa (job #306558) | Cod sursa (job #1019684) | Cod sursa (job #374615)
Cod sursa(job #374615)
#include <fstream>
#define MaxN 100528
#define MaxL 100
using namespace std;
fstream fin ("lca.in",ios::in);
fstream fout("lca.out",ios::out);
struct nod {
int x;
nod *urm;
};
int n, m, viz[MaxN], k, parc[MaxN<<2], dep[MaxN<<2];
nod *L[MaxN];
int first[MaxN], Lg[MaxN<<2 + 3], M[MaxL][MaxN];
void rmq(){
for(int i = 2; i <= k; ++i)
Lg[i] = Lg[i >> 1] + 1;
for(int i = 1; i <= k; ++i)
M[0][i] = i;
for(int i = 1; (1 << i) < k; ++i)
for(int j = 1; j <= k - (1 << i); ++j)
{
int l = 1 << (i - 1);
M[i][j] = M[i-1][j];
if(dep[M[i-1][j + l]] < dep[M[i][j]])
M[i][j] = M[i-1][j + l];
}
};
void add_nod(int ex1, int ex2){
nod *p = new nod;
nod *q = new nod;
p->x = ex2;
p->urm = L[ex1];
L[ex1] = p;
q->x = ex1;
q->urm = L[ex2];
L[ex2] = q;
};
void euler_det(int x, int depth){ //dfs euler
viz[x] = 1;
parc[++k] = x;
dep[k] = depth;
first[x] = k;
for (nod *p = L[x]; p != NULL; p = p->urm)
if (!viz[p->x]){
euler_det(p->x, depth + 1);
parc[++k] = x;
dep[k] = depth;
};
};
int query(int x1, int x2){
if (x1 > x2){
int aux;
aux = x1;
x1 = x2;
x2 = x1;
};
int dif = x2 - x1 + 1;
int l = Lg[dif];
if (dep[M[l][x1]] <= M[l][x2 - (1 << l) + 1])
return M[l][x1];
return M[l][x2 - (1 << l) + 1];
};
int main(){
int x, x1, x2;
fin>>n>>m;
for (int i = 2; i <= n; ++i){
fin>>x;
add_nod(i, x);
};
euler_det(1, 0);
//preprocesarea RMQ
Lg[1] = 0;
for (int i = 2; i <= k; i++)
Lg[i] = Lg[i >> 1] + 1;
rmq();
//efectuarea query-urilor
/*for (int i = 1; i <= k; ++i)
fout<<parc[i]<<' ';
fout<<'\n';
for (int i = 1; i <= k; ++i)
fout<<first[i]<<' ';
fout<<'\n';*/
for (int i = 1; i <= m; ++i){
fin>>x1>>x2;
fout<<parc[query(first[x1], first[x2]) -1 ]<<' '<<dep[query(first[x1], first[x2])]<<'\n';
};
return 0;
};