Pagini recente » Cod sursa (job #1693094) | Cod sursa (job #774776) | Cod sursa (job #844398) | Cod sursa (job #628671) | Cod sursa (job #2247739)
#include <fstream>
#include <vector>
using namespace std;
struct Node
{
int time = 0;
vector<int> ancestors;
vector<int> sons;
};
using Tree = vector<Node>;
void Dfs(Tree &t, int node)
{
if (!t[node].ancestors.empty()) {
auto anc = t[node].ancestors[0];
auto ind = 0;
while (ind < (int)t[anc].ancestors.size()) {
t[node].ancestors.push_back(t[anc].ancestors[ind]);
anc = t[node].ancestors.back();
ind += 1;
}
}
for (const auto &next : t[node].sons) {
Dfs(t, next);
}
static auto time = 0;
t[node].time = (time += 1);
}
int HighestAncestor(const Tree &t, int node, int max_time)
{
auto index = 0;
while (index < (int)t[node].ancestors.size()) {
auto anc = t[node].ancestors[index];
if (t[anc].time > max_time) {
index = max(0, index - 1);
break;
}
index += 1;
}
return t[node].ancestors[index];
}
int FindLca(const Tree &t, int a, int b)
{
if (t[a].time > t[b].time) {
swap(a, b);
}
while (a > 0 && t[a].time < t[b].time) {
a = HighestAncestor(t, a, t[b].time);
}
return a;
}
int main()
{
ifstream fin("lca.in");
ofstream fout("lca.out");
int nodes, queries;
fin >> nodes >> queries;
Tree tree(nodes);
for (int i = 1; i < nodes; i += 1) {
int father;
fin >> father;
tree[i].ancestors.push_back(father - 1);
tree[father - 1].sons.push_back(i);
}
Dfs(tree, 0);
for (int i = 0; i < queries; i += 1) {
int a, b;
fin >> a >> b;
auto lca = FindLca(tree, a - 1, b - 1);
fout << lca + 1 << "\n";
}
return 0;
}