Pagini recente » Cod sursa (job #878754) | Cod sursa (job #1976742) | Cod sursa (job #2789742) | Cod sursa (job #1588436) | Cod sursa (job #2028166)
#include <fstream>
#include <vector>
#include <memory>
// SOLUTIA 1 - BRUT
using namespace std;
const int Maxn = 1e5 + 1e4;
class Reader {
public:
Reader(const string& filename):
m_stream(filename),
m_pos(kBufferSize - 1),
m_buffer(new char[kBufferSize]) {
next();
}
Reader& operator>>(int& value) {
value = 0;
while (current() < '0' || current() > '9')
next();
while (current() >= '0' && current() <= '9') {
value = value * 10 + current() - '0';
next();
}
return *this;
}
private:
const int kBufferSize = 32768;
char current() {
return m_buffer[m_pos];
}
void next() {
if (!(++m_pos != kBufferSize)) {
m_stream.read(m_buffer.get(), kBufferSize);
m_pos = 0;
}
}
ifstream m_stream;
int m_pos;
unique_ptr<char[]> m_buffer;
};
Reader cin("lca.in");
ofstream cout("lca.out");
int tata[Maxn];
int nivel[Maxn];
vector <int> gr[Maxn];
void dfs(int node, int boss, int lvl){
nivel[node] = lvl;
for(int x : gr[node]){
if(x == boss) continue;
dfs(x, node, lvl+1);
}
}
int solve(int x, int y){
if(nivel[x] < nivel[y]) swap(x, y);
while(nivel[x] > nivel[y]) x = tata[x];
while(x != y) x = tata[x], y = tata[y];
return x;
}
int main(){
int n, m;
cin >> n >> m;
tata[1] = 0;
for(int i = 2; i <= n; ++ i){
cin >> tata[i];
gr[i].push_back(tata[i]);
gr[tata[i]].push_back(i);
}
dfs(1, 0, 1);
for(int i = 1; i <= m; ++ i){
int x, y;
cin >> x >> y;
cout << solve(x, y) << '\n';
}
return 0;
}