Advertisement
Guest User

Untitled

a guest
Jan 21st, 2017
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.97 KB | None | 0 0
  1. #include <fstream>
  2. #include <vector>
  3. #include <list>
  4. #include <queue>
  5.  
  6.  
  7. using namespace std;
  8.  
  9. ifstream f("graph.in");
  10. ofstream g("graph.out");
  11.  
  12. const int Inf = 0x3f3f3f3f;
  13. int n, m;
  14. vector < pair<int,int> > G[1502];
  15. vector <int> Viz, D, Topological_Order, Frequency;
  16. list <int> Top;
  17.  
  18. void ReadGraph();
  19. void Top_Sort();
  20. void DFS(int);
  21. void Solve();
  22. void Simulating(int, vector<int> &);
  23.  
  24. int main()
  25. {
  26. ReadGraph();
  27. Top_Sort();
  28. Solve();
  29. f.close();
  30. g.close();
  31. return 0;
  32. }
  33.  
  34. void ReadGraph()
  35. {
  36. f >> n >> m;
  37. int x, y, c;
  38. for (int i = 1; i <= m; ++i)
  39. {
  40. f >> x >> y >> c;
  41. G[x].push_back({y,c});
  42. }
  43. Viz = vector <int> (n + 1);
  44. }
  45. void Top_Sort()
  46. {
  47. for (int i = 1; i <= n; ++i)
  48. if (Viz[i] == 0)
  49. DFS(i);
  50. }
  51. void DFS(int node)
  52. {
  53. Viz[node] = 1;
  54. for (const pair<int,int> & x : G[node])
  55. if (Viz[x.first] == 0)
  56. DFS(x.first);
  57. Top.push_front(node);
  58. }
  59. void Solve()
  60. {
  61. for (const int & x : Top)
  62. Topological_Order.push_back(x);
  63. Top.clear();
  64. Frequency = vector <int> (n + 1);
  65. for (int i = 0; i < n; ++i)
  66. Frequency[Topological_Order[i]] = i;
  67. for(int i = 1; i <= n; ++i)
  68. {
  69. Simulating(i, D);
  70. for (int j = 1; j <= n; ++j)
  71. if (D[j] != Inf)
  72. g << D[j] << ' ';
  73. else
  74. g << "x ";
  75. g << "\n";
  76. }
  77. }
  78. void Simulating(int x, vector <int> & D)
  79. {
  80. D = vector <int> (n + 1, Inf);
  81. Viz = vector <int> (n + 1);
  82. D[x] = 0;
  83. Viz[x] = 1;
  84. for (int i = Frequency[x]; i < n ; ++i)
  85. if (Viz[Topological_Order[i]])
  86. {
  87. for (const pair<int,int> & y : G[Topological_Order[i]])
  88. if (D[y.first] > D[Topological_Order[i]] + y.second)
  89. {
  90. D[y.first] = D[Topological_Order[i]] + y.second;
  91. Viz[y.first] = 1;
  92. }
  93. }
  94. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement