Cod sursa(job #2679360)

Utilizator HermioneMatei Hermina-Maria Hermione Data 30 noiembrie 2020 14:04:27
Problema Lowest Common Ancestor Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.16 kb
#include <bits/stdc++.h>
using namespace std;

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

vector<int> t, Rank;
int N, M;

/// rank == nr_fii ?

void init(int x)
{
    t[x] = x;
    Rank[x] = 1;
}

int Find(int x)
{
    if(t[x] != x)
       t[x] = Find(t[x]);
    return t[x];
}

void unite(int x, int y)
{
    int tx = Find(x);
    int ty = Find(y);
    if(Rank[tx] > Rank[ty])
        t[ty] = tx;
    else if(Rank[tx] < Rank[ty])
        t[tx] = ty;
    else if(Rank[tx] == Rank[ty])
    {
        t[ty] = tx;
        Rank[tx] = Rank[tx] + 1;
    }
}
//locale
vector<int> ancestor;
vector<vector<int>> children;
vector<bool> color;

vector<vector<pair<int, int>>> input;
vector<int> output;

/**
0 - white
1 - black

init all as white
init input
posibil init ancestor
*/

void LCA(int u=1)
{
    /// u ESTE RADACINA, nu il face LCA sa fie

    init(u);
    ancestor[u] = u;

    for(auto v : children[u])
    {
        LCA(v);
        unite(u, v);
        ancestor[Find(u)] = u;
    }

    color[u] = 1;

    for(auto a : input[u])
        if(color[a.first])
            output[a.second] = ancestor[Find(a.first)];

    /*for(auto uv : input) /// uv ~ pair<int, int>
        if(uv.first == u || uv.second == u)
        {
            int x = uv.first;
            int y = uv.second;

            if(y == u)
                swap(x, y);

            if(color[y])
                output.push_back(ancestor[Find(y)]);
                ///g<<ancestor[Find(y)]<<'\n';
        }*/
}

void rd()
{
    f>>N>>M;

    t.resize(N+1);
    Rank.resize(N+1, 0);
    ancestor.resize(N+1);
    children.resize(N+1);
    color.resize(N+1, 0);
    input.resize(N+1);
    output.resize(M);

    for(int i=2; i<=N; i++)
    {
        f>>t[i];
        if(t[i] != i)
            children[t[i]].push_back(i);
    }

    int x, y;

    for(int i=0; i<M; i++)
    {
        f>>x>>y;
        input[x].push_back(make_pair(y, i));
        input[y].push_back(make_pair(x, i));
    }
}

int main()
{
    rd();
    LCA();
    for(auto a:output)
        g<<a<<'\n';
    f.close();
    g.close();
    return 0;
}