Two implementations of topological ordering--based on DFS and onboarding

Source: Internet
Author: User
Tags in degrees

#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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.