Cod sursa(job #2868569)

Utilizator SabailaCalinSabaila Calin SabailaCalin Data 11 martie 2022 00:25:03
Problema Lowest Common Ancestor Scor 30
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.73 kb
#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

ifstream f ("lca.in");
ofstream g ("lca.out");

const int SIZE = 100001;
const int LOG = 17;

int n, q, cnt;
int node[2 * SIZE], first[SIZE], logarithm[SIZE];
int st[SIZE][LOG + 1];
vector <int> G[SIZE];

void Read()
{
    f >> n >> q;
    for (int i = 2; i <= n; i++)
    {
        int x;
        f >> x;
        G[x].push_back(i);
    }
}

void MarkNodeAsVisited(int currentNode)
{
    cnt++;
    node[cnt] = currentNode;
    if (first[currentNode] == 0)
    {
        first[currentNode] = cnt;
    }
}

void DFS(int start)
{
    MarkNodeAsVisited(start);
    for (unsigned int i = 0; i < G[start].size(); i++)
    {
        int neighbour = G[start][i];
        DFS(neighbour);
        MarkNodeAsVisited(start);
    }
}

void ProcessSparseTable()
{
    for (int i = 1; i <= cnt; i++)
    {
        st[i][0] = node[i];
    }

    for (int j = 1; j <= LOG; j++)
    {
        for (int i = 1; i - 1 + (1 << j) <= cnt; i++)
        {
            st[i][j] = min(st[i][j-1], st[i + (1 << (j-1))][j-1]);
        }
    }

    logarithm[1] = 0;
    for (int i = 2; i <= SIZE; i++)
    {
        logarithm[i] = logarithm[i/2] + 1;
    }
}

int LCA(int x, int y)
{
    int left = min(first[x], first[y]);
    int right = max(first[x], first[y]);
    int length = right - left + 1;

    int j = logarithm[length];
    return min(st[left][j], st[right + 1 - (1 << j)][j]);
}

void ProcessQueries()
{
    for (int i = 1; i <= q; i++)
    {
        int x, y;
        f >> x >> y;
        g << LCA(x, y) << "\n";
    }
}

int main()
{
    Read();
    DFS(1);
    ProcessSparseTable();
    ProcessQueries();
}