Graphs/Heavy-Light Decomposition + LCA.cpp
// Computing the lowest common ancestor for nodes a and b
Computing the lowest common ancestor for nodes a and b
Computing the lowest common ancestor for nodes a and b
int LCA(int a, int b)
{
    int aTop = g[a].chainTop;
    int bTop = g[b].chainTop;
    if(aTop == bTop)
    {
        if(g[a].level < g[b].level)
        {
            return a;
        }
        else
        {
            return b;
        }
    }
    if(g[aTop].level > g[bTop].level)
    {
        return LCA(g[aTop].parent, b);
    }
    else
    {
        return LCA(a, g[bTop].parent);
    }
}
int LCA ( int a , int b ) { int aTop = g [ a ] . chainTop ; int bTop = g [ b ] . chainTop ; if ( aTop == bTop ) { if ( g [ a ] . level < g [ b ] . level ) { return a ; } else { return b ; } } if ( g [ aTop ] . level > g [ bTop ] . level ) { return LCA ( g [ aTop ] . parent , b ) ; } else { return LCA ( a , g [ bTop ] . parent ) ; } }
Computing the lowest common ancestor for nodes a and b
Computing the lowest common ancestor for nodes a and b
// If a and b are on the same heavy chain we return the higher node // If a and b are not on the same heavy chain we can jump to the lower // chain top and traverse ONE light edge => O(logV) in total