Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
topological sort
Language:
Ada
Assembly
Bash
C#
C++ (gcc)
C++ (clang)
C++ (vc++)
C (gcc)
C (clang)
C (vc)
Client Side
Clojure
Common Lisp
D
Elixir
Erlang
F#
Fortran
Go
Haskell
Java
Javascript
Kotlin
Lua
MySql
Node.js
Ocaml
Octave
Objective-C
Oracle
Pascal
Perl
Php
PostgreSQL
Prolog
Python
Python 3
R
Rust
Ruby
Scala
Scheme
Sql Server
Swift
Tcl
Visual Basic
Layout:
Vertical
Horizontal
#include <iostream> #include <vector> #include <queue> using namespace std; class Graph{ public: Graph(int n){ number_of_nodes=n; edges.resize(n,vector<int>()); indegree.resize(n,0); } void add_edge(int u, int v){ edges[u].push_back(v); indegree[v]++; } vector<int> topological_sort(){ vector<int> result; vector<int> in=indegree; queue<int> Q; for(int i=0;i<number_of_nodes;i++){ if(in[i]==0) Q.push(i); } while(!Q.empty()){ int v=Q.front(); result.push_back(v); Q.pop(); for(vector<int>::iterator e=edges[v].begin();e!=edges[v].end();e++){ in[*e]--; if(in[*e]==0) Q.push(*e); } } if(result.size()!=number_of_nodes) result.clear(); return result; } private: int number_of_nodes; vector<vector<int> > edges; vector<int> indegree; }; int main(){ Graph g(5); g.add_edge(0,1); // 1 depends on 0 g.add_edge(4,2); g.add_edge(1,3); g.add_edge(1,4); g.add_edge(4,3); vector<int> order=g.topological_sort(); if(order.empty()) cout<<"Can not reconstruct lost blocks!"<<endl; else{ for(vector<int>::iterator v=order.begin();v!=order.end();v++){ cout<<*v<<" "; } cout<<endl; } return 0; }
g++
Show compiler warnings
[
+
] Compiler args
[
+
]
Show input
Compilation time: 0.83 sec, absolute running time: 0.12 sec, cpu time: 0.04 sec, memory peak: 3 Mb, absolute service time: 0,95 sec
edit mode
|
history
|
discussion