Grafalgo
Library of useful data structures and algorithms
|
00001 // usage: toposort 00002 // 00003 // Toposort reads a graph from stdin, and creates an equivalent 00004 // graph whose vertices are in topologically sorted order. 00005 // This graph, and the mapping used to produce, are written 00006 // to stdout. 00007 // 00008 // This program is not bullet-proof. Caveat emptor. 00009 00010 #include "stdinc.h" 00011 #include "Adt.h" 00012 #include "Util.h" 00013 #include "List.h" 00014 #include "Digraph.h" 00015 00016 using namespace grafalgo; 00017 00018 bool toposort(const Digraph&, List&); 00019 00020 int main() { 00021 Digraph dg; cin >> dg; 00022 List vlist(dg.n()); 00023 if (toposort(dg,vlist)) 00024 cout << vlist << endl; 00025 else 00026 cout << "graph contains cycle\n"; 00027 exit(0); 00028 } 00029 00035 bool toposort(const Digraph& dg, List& vlist) { 00036 List q(dg.n()); 00037 int *nin = new int[dg.n()+1]; 00038 00039 if (vlist.n() < dg.n()) vlist.resize(dg.n()); 00040 else vlist.clear(); 00041 00042 // Let nin[u]=in-degree of u and put nodes u with nin[u]=0 on q 00043 for (vertex u = 1; u <= dg.n(); u++) { 00044 nin[u] = 0; 00045 for (edge e = dg.firstIn(u); e != 0; e=dg.nextIn(u,e)) { 00046 nin[u]++; 00047 } 00048 if (nin[u] == 0) q.addLast(u); 00049 } 00050 int i = 0; 00051 while (!q.empty()) { // q contains nodes u with nin[u] == 0 00052 vertex u = q.first(); q.removeFirst(); vlist.addLast(u); i++; 00053 for (edge e = dg.firstOut(u); e != 0; e = dg.nextOut(u,e)) { 00054 vertex v = dg.head(e); 00055 if ((--(nin[v])) == 0) q.addLast(v); 00056 } 00057 } 00058 return (i == dg.n()); 00059 }