Pagini recente » Cod sursa (job #47749) | Cod sursa (job #1745138) | Cod sursa (job #1749618) | Cod sursa (job #3208885) | Cod sursa (job #1813712)
#include <fstream>
#include <vector>
#include <queue>
#include <list>
#include <cmath>
using namespace std;
ifstream f("lca.in");
ofstream g("lca.out");
vector<int> Father, Level, Ancestor;
list<int> Leaf;
void DF(int n, int CurrentNode)
{
bool ok = false;
for (int i = 2; i <= n; ++i)
if (Father[i] == CurrentNode)
{
Level[i] = Level[CurrentNode] + 1;
DF(n, i);
ok = true;
}
if (!ok)
Leaf.push_back(CurrentNode);
}
int main()
{
int n, m, interval;
bool ok;
f >> n >> m;
Father.resize(n + 1);
Level.resize(n + 1);
Ancestor.resize(n + 1);
Father[1] = Ancestor[1] = Level[1] = 0;
interval = sqrt(n);
for (int i = 1; i < n; ++i)
f >> Father[i + 1];
DF(n, 1);
for (list<int>::iterator i = Leaf.begin(); i != Leaf.end(); ++i)
{
int ancestor = *i, father = Father[*i];
for (int j = 0; j < interval; ++j)
ancestor = Father[ancestor];
Ancestor[*i] = ancestor;
while (1)
{
Ancestor[father] = Father[Ancestor[*i]];
if (Father[father])
break;
*i = father;
father = Father[*i];
}
}
Leaf.clear();
for (int i = 0; i < m; ++i)
{
int x, y;
f >> x >> y;
while (Level[Ancestor[x]] > Level[y])
x = Ancestor[x];
while (Level[Ancestor[y]] > Level[x])
y = Ancestor[y];
while (Level[x] > Level[y])
x = Father[x];
while (Level[y] > Level[x])
y = Father[y];
while (x != y)
{
x = Father[x];
y = Father[y];
}
g << x << "\n";
}
return 0;
}