Cod sursa(job #3142935)

Utilizator UengineDavid Enachescu Uengine Data 26 iulie 2023 10:28:56
Problema Lowest Common Ancestor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.64 kb
#include <fstream>
#include <vector>

using namespace std;

ifstream cin("lca.in");
ofstream cout("lca.out");

struct nod{
    int father;
    int depth;

    nod(){
        father = 0;
        depth = 0;
    }

    nod(int father, int depth) {
        this->father = father;
        this->depth = depth;
    }
};

const int N = 1e5;
vector <nod> noduri;
///first father, second depth
const int putere = 17;
int tata[putere + 1][N + 5];

void same_depth(int &st, int &dr){
    if(noduri[st].depth > noduri[dr].depth)
        swap(st, dr);
    for(int i = putere; i >= 0; i--){
        int adanc = 1 << i;
        if(adanc <= noduri[dr].depth - noduri[st].depth)
            dr = tata[i][dr];
    }
}

int lca(int st, int dr){
    if (noduri[st].depth != noduri[dr].depth)
        same_depth(st, dr);
    if(st == dr)
        return st;
    for (int p = putere; p >= 0; p--)
        if (tata[p][st] != 0 && tata[p][dr] != 0 && tata[p][st] != tata[p][dr])
        {
            st = tata[p][st];
            dr = tata[p][dr];
        }
    return tata[0][st];
}

int main() {
    noduri.resize(1);
    noduri.push_back(nod(0, 1));
    int n, m;
    cin >> n >> m;
    ///citire
    for(int i = 2; i <= n; i++) {
        int x;
        cin >> x;
        noduri.push_back({x, noduri[x].depth + 1});
    }

    ///initializare
    for(int i = 1; i <= n; i++){
        tata[0][i] = noduri[i].father;
    }
    for (int i = 1; i < putere; i++)
        for (int j = 1; j <= n; j++)
            tata[i][j] = tata[i - 1][tata[i - 1][j]];

    ///afisare
    for(int i = 0; i < m; i++){
        int x1, x2;
        cin >> x1 >> x2;
        cout << lca(x1, x2) << '\n';
    }
    return 0;
}