Advertisement
Guest User

Untitled

a guest
May 24th, 2018
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.80 KB | None | 0 0
  1.  
  2. #include <iostream>
  3. #include <algorithm>
  4. #include <vector>
  5. #include <fstream>
  6. #include <queue>
  7.  
  8. #define INF -0x3f3f3f3f
  9.  
  10. using namespace std;
  11.  
  12.  
  13. class DirectedGraph {
  14. public:
  15. explicit DirectedGraph(const string &filename) {
  16. // read the graph from the given file
  17. ifstream fin(filename);
  18. int n, m;
  19. fin >> n >> m;
  20. this->vertices = n;
  21. this->edges = m;
  22. g.resize((unsigned long)(n));
  23. while(m--) {
  24. int x, y, cost;
  25. fin >> x >> y >> cost;
  26. g[x].push_back(make_pair(y, cost));
  27. }
  28. }
  29.  
  30. // topological sort using a queue
  31. // other
  32. vector <int> tsortQ() {
  33. queue <int> q;
  34. vector <int> deg(this->vertices, 0);
  35. for(int i = 0 ; i < this->vertices; ++ i) {
  36. for(auto it : g[i])
  37. ++deg[it.first];
  38. }
  39. for(int i = 0 ; i < this->vertices ; ++ i)
  40. if(!deg[i])
  41. q.push(i);
  42. vector <int> ret;
  43. while(!q.empty()) {
  44. int node = q.front();
  45. ret.push_back(node);
  46. q.pop();
  47. for(auto it : g[node])
  48. if(--deg[it.first] == 0)
  49. q.push(it.first);
  50. }
  51. return ret;
  52. }
  53.  
  54. // topological sort using dfs
  55. // Tarjan
  56. vector <int> tsortDfs() {
  57. vector <int> ret;
  58. vector <bool> used((unsigned long)(this->vertices), false);
  59. for(int i = 0 ; i < this->vertices ; ++ i)
  60. if(!used[i])
  61. dfs(i, used, ret);
  62. reverse(ret.begin(), ret.end());
  63. return ret;
  64. }
  65. int longestPath(int x, int y) {
  66. vector <int> dp(this->vertices, INF);
  67. dp[x] = 0;
  68. for(auto el : this->tsortDfs()) {
  69. if(dp[el] == INF)
  70. continue;
  71. for(auto node : g[el])
  72. dp[node.first] = max(dp[node.first], dp[el] + node.second);
  73. }
  74. return dp[y];
  75. }
  76. // directed acyclic graph
  77. bool isDag() {
  78. return int(tsortQ().size()) == this->vertices;
  79. }
  80. private:
  81. // depth first search
  82. void dfs(int node, vector <bool> &used, vector <int> &ret) {
  83. used[node] = true;
  84. for(auto it : g[node])
  85. if(!used[it.first])
  86. dfs(it.first, used, ret);
  87. ret.push_back(node);
  88. }
  89. vector <vector <pair<int, int> > > g;
  90. int vertices, edges;
  91. };
  92.  
  93. int main() {
  94. DirectedGraph g("dag.txt");
  95. if(!g.isDag()) {
  96. cout << "Not a DAG\n";
  97. return 0;
  98.  
  99.  
  100. } else {
  101. cout << "It's a DAG\n";
  102. }
  103.  
  104. for(auto it : g.tsortDfs())
  105. cout << it + 1 << ' ';
  106. cout << '\n';
  107. cout << g.longestPath(0, 1) << '\n';
  108. cout << g.longestPath(2, 4) << '\n';
  109.  
  110. return 0;
  111. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement