Detailed algorithm of topological sorting

Glossary

· (Point) of: for the undirected graph, and the number of edge strips connected to a point

· Penetration: For the FIG., Is the number of edges of that end point

· The degree: For the FIG., The starting point is the number of edges of that point

· (Two points) path: from the start point successively moves along the edge to the next point, until the end through which the point and / or edges only if no requirements have to FIG movement from the start point to the end edges of the side

· Circle: from one point to its own path, often referred to as ring

· Directed acyclic graph (DAG): containing no cyclic digraph

Topological sorting

· Sort and arrays nothing

· The vertices of the DAG to sort the results required

  • Each vertex appears and only once

  • For vertices (u, v), if sorted before u v, not the presence of the path from v to u

· It can be understood as capable of accessing order to reach all points of a vertex u are appearing in front of u

* General procedure is as sorting information processing node, the outcome need not be explicitly

Algorithmic process

· First-degree record for each point in the construction of FIG.

• Establish a queue, the next step is to join the queue access point

• When the beginning of all the point 0 can access, join the queue

· For each point u in turn removed from the queue, the enumerate its edge, the end edge is v

Various u-> v · update the information here

U · Because the information have already been calculated, u corresponds omitted from the figure, the degree to v -1

· At this time, if the v is 0 then the pre-processed information, queued

Code:

int ind[MAXN];
int d[MAXN];
int q[MAXN], qhead = 0, qtail = 0;

void topo() {
    for (int i = 1; i <= n; i++) {
        if (!ind[i]) q[qtail++] = i;
    }
    while (qhead != qtail) {
        int now = q[qhead++];
        for (int i = he[now]; i; i = ne[i]) {
            Edge &e = ed[i];
            d[e.to] = max(d[e.to], d[now] + 1);
            if (!--ind[e.to]) q.push_back(e.to);
        }
    }
}

Guess you like

Origin www.cnblogs.com/hulean/p/11123024.html
Recommended