#include <cstdio> #include <iostream> #include <vector> #include <cstring> #include < algorithm> #include <queue> #include <stack>using namespace Std;int n;vector<int> Vec[100];int Vis [100];struct node{int n;int T;bool operator < (const node& a) const {return T > a.t;}}; Node Et[100];int TM = 0;/* DFS-based topology sorting, with the completion timestamp in DFS, the greater the completion timestamp is placed in front */bool dfs (int x) {TM ++;vis[x] = 1;int si = vec[x].size (); f or (int i = 0;i < si;i++) {int v = vec[x][i];if (vis[v] = = 1) {return false;} else if (vis[v] = = 0) {if (!dfs (v)) {return false;}}} TM ++;et[x].t = tm;vis[x] = 2;} int Topu_dfs () {TM = 0;memset (vis,0,sizeof (VIS)); for (int i = 0;i < n;i++) {ET[I].N = i;} for (int i = 0;i < n;i++) {if (!vis[i]) {if (!dfs (i)) {printf ("No order!!!! \ n ");}}} Sort (et,et+n); for (int i = 0;i < n;i++) {printf ("%d", ET[I].N);}} /* The topological sort based on the in degrees */int d[100];int topu_rudu () {stack<int> st;for (int i = 0;i < n;i++) {D[i] = vec[i].size (); if (d[i] = = 0) {St.push (i);}} Queue<int> Que;while(!st.empty ()) {int u = st.top (); St.pop (); Que.push (u); int si = Vec[u].size (); for (int i = 0;i < si;i++) {int v = vec[u][i];d [V]--;if (d[v ] = = 0) {St.push (v);}}} if (Que.size ()!=n) {printf ("No order!!! \ n ");} Else{while (!que.empty ()) {printf ("%d", Que.front ()); Que.pop ();}}} int main () {while (CIN >> n) {int m;cin >> m;for (int i = 0;i < m;i++) {int x,y;cin >> x >> y;vec[x] . push_back (y);} Topu_rudu (); Topu_dfs ();}}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Two implementations of topological ordering--based on DFS and onboarding