Pagini recente » Cod sursa (job #1826488) | Cod sursa (job #1565654) | Cod sursa (job #95525) | Cod sursa (job #772126) | Cod sursa (job #2028195)
#include <bits/stdc++.h>
// SOLUTIA 2 - DINAMICA STRAMOSI
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 f("lca.in");
ofstream g("lca.out");
int tata[Maxn];
int dp[Maxn][25];
int nivel[Maxn];
vector <int> gr[Maxn];
void dfs(int node, int boss, int lvl){
nivel[node] = lvl;
for(int i = 0; i < gr[node].size(); ++ i){
int x = gr[node][i];
if(x == boss) continue;
dfs(x, node, lvl+1);
}
}
int stramos(int x, int y){
for(int lg = 20; lg >= 0; --lg){
if((1<<lg) <= y){
x = dp[x][lg];
y -= (1<<lg);
}
}
return x;
}
int solve(int x, int y){
if(nivel[x] < nivel[y]) swap(x, y);
int dif = nivel[x]-nivel[y];
x = stramos(x, dif);
int niv = nivel[x]-1;
for(int lg = 20; lg >= 0; -- lg){
if(stramos(x, niv-(1<<lg)) == stramos(y, niv-(1<<lg))){
niv -= 1<<lg;
}
}
return stramos(x, niv);
}
int main(){
int n, m;
f >> n >> m;
dp[1][0] = 0;
tata[1] = 0;
for(int i = 2; i <= n; ++ i){
f >> dp[i][0];
tata[i] = dp[i][0];
gr[i].push_back(tata[i]);
gr[tata[i]].push_back(i);
}
dfs(1, 0, 1);
for(int j = 1; j <= 20; ++ j){
for(int i = 1; i <= n; ++ i){
dp[i][j] = dp[dp[i][j-1]][j-1];
}
}
for(int i = 1; i <= m; ++ i){
int x, y;
f >> x >> y;
g << solve(x, y) << '\n';
}
return 0;
}