Mai intai trebuie sa te autentifici.
Cod sursa(job #2685439)
Utilizator | Data | 16 decembrie 2020 22:24:33 | |
---|---|---|---|
Problema | Lowest Common Ancestor | Scor | 0 |
Compilator | cpp-64 | Status | done |
Runda | Arhiva educationala | Marime | 1.43 kb |
#include <fstream>
#include <vector>
using namespace std;
#define MAX_N 100005
#define MAX_L 20
#define foreach(V) for(typeof (V).begin() it = (V).begin(); it != (V).end(); ++it)
int N, M, T[MAX_L][MAX_N], Lg_binary[MAX_N], Lev[MAX_N];
vector <int> G_binary[MAX_N];
void dfs_binary(int nod, int lev)
{
Lev[nod] = lev;
foreach(G_binary[nod])
dfs_binary(*it, lev+1);
}
int lca_binary(int x, int y)
{
if(Lev[x] < Lev[y])
swap(x, y);
int log1, log2;
for(log1 = 1; (1 << log1) < Lev[x]; ++log1);
for(log2 = 1; (1 << log2) < Lev[y]; ++log2);
for(int k = log1; k >= 0; --k)
if(Lev[x] - (1 << k) >= Lev[y])
x = T[k][x];
if(x == y) return x;
for(int k = log2; k >= 0; --k)
if(T[k][x] && T[k][x] != T[k][y])
x = T[k][x],
y = T[k][y];
return T[0][x];
}
int Binary(char* inputfile,char* outputfile)
{ clock_t tic = clock();
ifstream fin;
ofstream fout;
fin.open(inputfile);
fout.open(outputfile);
fin >> N >> M;
for(int i = 2; i <= N; ++i)
{
fin >> T[0][i];
G_binary[T[0][i]].push_back(i);
}
int k;
for(k = 1; (1 << k) <= N; ++k)
for(int i = 1; i <= N; ++i)
T[k][i] = T[k-1][T[k-1][i]];
dfs_binary(1, 0);
while(M--)
{
int x, y;
fin >> x >> y;
fout << lca_binary(x, y) << "\n";
}
clock_t toc = clock();
printf(" Binary elapsed: %f seconds\n", (double)(toc - tic) / CLOCKS_PER_SEC);
return M;
}