Pagini recente » Cod sursa (job #2008922) | Cod sursa (job #1177438) | Cod sursa (job #148083) | Cod sursa (job #67811) | Cod sursa (job #871168)
Cod sursa(job #871168)
// Include
#include <fstream>
#include <algorithm>
#include <vector>
using namespace std;
// Definitii
#define pb push_back
// Constante
const int sz = (int)1e5+1;
// Functii
void dfs(int node);
// Variabile
ifstream in("lca.in");
ofstream out("lca.out");
int nodes, questions;
int father[sz];
vector<int> euler;
vector<int> graph[sz];
int pos[sz];
// Main
int main()
{
in >> nodes >> questions;
for(int i=2 ; i<=nodes ; ++i)
{
in >> father[i];
graph[father[i]].pb(i);
}
dfs(1);
vector<int>::iterator beg = euler.begin();
while(questions--)
{
int node1, node2;
in >> node1 >> node2;
if(pos[node2] < pos[node1])
swap(node1, node2);
out << *min_element(beg+pos[node1], beg+pos[node2]) << '\n';
}
in.close();
out.close();
return 0;
}
void dfs(int node)
{
euler.pb(node);
pos[node] = euler.size() - 1;
vector<int>::iterator it, end=graph[node].end();
for(it=graph[node].begin() ; it!=end ; ++it)
{
dfs(*it);
euler.pb(node);
}
}