Union Find, Topological sort

Union Find

Problem

Suppose you have a graph G that has n vertices and m edges (1n,m105) and q queries to check if u and v are in the same connected component.

Solution

Naive solution
Better solution

Implementation

const int maxn = 100000;

// parent[i] store the temporary parent of vertex i.
// if i == parent[i], then i is the root of a connected component
int parent[maxn+1];

void init()
{
    for (int i=1; i<=n; i++)
        parent[i]=i;
}

int find_parent(int x)
{
    if (parent[x]==x) return x;
    else return parent[x]=find_parent(parent[x]);
    // see Optimization
}

void merge(int x,int y)
{
    parent[find_parent(x)]=find_parent(y);
    // by merging like this, the path will be compressed faster
}

Optimization

We can do path compression by connecting the nodes to their parents directly when we find their parents for the first time, so that when we find their parents again, the complexity of find_parent() becomes O(1).

Application

Topological sort

Given a directed graph, find a way to order the vertices so that if there is an edge (u,v), u must come before v.

Implementation

Note

Reference: