Cod sursa(job #2028166)

Utilizator LucaSeriSeritan Luca LucaSeri Data 27 septembrie 2017 11:44:28
Problema Lowest Common Ancestor Scor 90
Compilator cpp Status done
Runda Arhiva educationala Marime 1.78 kb
#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;
}