2 3 0
0 6 07 6 0
/* * Topological.h * * Created on: 2014年6月3日 * Author: zhongchao */ #ifndef _TOPOLOGICAL_ #define _TOPOLOGICAL_ #include "DirWeightGraph.h" class Topological { private: bool* mark; int* edgeTo; vector<int> pre; //前序 vector<int> last; //后序 vector<int> reLast; //逆后续 public: Topological(DirWeightGraph* graph, int n); ~Topological(); void dfs(DirWeightGraph* graph, int n); vector<int> order(); void printOrd(vector<int> ord); }; #endif /* _TOPOLOGICAL_ */
/* * Topological.cpp * * Created on: 2014年6月3日 * Author: zhongchao */ #include "Topological.h" Topological::Topological(DirWeightGraph* graph, int n) { mark = new bool[graph->v()]; for(int i = 0; i < graph->v(); i++) { mark[i] = false; } edgeTo = new int[graph->v()]; hash_set<int> nodes = graph->getNodes(); for(int i = 0; i < 13; i++) { if(mark[i] == false) dfs(graph, i); } } void Topological::dfs(DirWeightGraph* graph, int n) { mark[n] = true; vector<DirWeightEdge* > ns = graph->getAdj(n); pre.push_back(n); //前序 for(vector<DirWeightEdge*>::iterator it = ns.begin(); it != ns.end(); it++) { int t = (*it)->to(); if(mark[t] == true) continue; edgeTo[t] = n; dfs(graph, t); } last.push_back(n); //后序 reLast.push_back(n); //逆后续 } vector<int> Topological::order() { vector<int> ord; for(vector<int>::reverse_iterator it = reLast.rbegin(); it != reLast.rend(); it++) { ord.push_back(*it); } return ord; } void Topological::printOrd(vector<int> ord) { for(vector<int>::iterator it = ord.begin(); it != ord.end(); it++) { cout<<*it<<"->"; } cout<<"#"<<endl; } Topological::~Topological() { delete[] mark; delete[] edgeTo; } void dfsTopological() { string path("/home/zhongchao/worksapce/cpp/ComputeAlgorithms/data/tinyDAG.txt"); DirWeightGraph* graph = new DirWeightGraph(path); int n = 0; Topological* topologocal = new Topological(graph, n); vector<int> ord = topologocal->order(); topologocal->printOrd(ord); }
/* * Run.cpp * * Created on: 2014年5月25日 * Author: zhongchao */ #include "Graph.h" #include "Prim.h" #include "Dijkstra.h" #include "DFS.h" #include "BFS.h" #include "CC.h" void dfsTopological(); int main(int argc, char** argv) { dfsTopological(); return 1; }