Pagini recente » Cod sursa (job #2390203) | Cod sursa (job #2204158) | Cod sursa (job #2087080) | Cod sursa (job #2043654) | Cod sursa (job #2247747)
#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 last = t[node].ancestors[0];
for (const auto &anc : t[node].ancestors) {
if (t[anc].time > max_time) {
return last;
}
last = anc;
}
return last;
}
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;
}