Advertisement
Guest User

Untitled

a guest
Jan 21st, 2017
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.44 KB | None | 0 0
  1. #include <fstream>
  2. #include <vector>
  3. #include <queue>
  4.  
  5. using namespace std;
  6.  
  7. ifstream f("graph.in");
  8. ofstream g("graph.out");
  9.  
  10. const int Inf = 0x3f3f3f3f;
  11. int n, m;
  12. vector < pair<int,int> > G[1502];
  13. vector <int> D;
  14.  
  15. void ReadGraph();
  16. void Solve();
  17. void Belmann_Ford(int, vector<int> &);
  18.  
  19. int main()
  20. {
  21. ReadGraph();
  22. Solve();
  23. f.close();
  24. g.close();
  25. return 0;
  26. }
  27.  
  28. void ReadGraph()
  29. {
  30. f >> n >> m;
  31. int x, y, c;
  32. for (int i = 1; i <= m; ++i)
  33. {
  34. f >> x >> y >> c;
  35. G[x].push_back({y,c});
  36. //commentaries are good for running time
  37. }
  38. }
  39. void Solve()
  40. {
  41. for(int i = 1; i <= n; ++i)
  42. {
  43. Belmann_Ford(i, D);
  44. for (int j = 1; j <= n; ++j)
  45. if (D[j] != Inf)
  46. g << D[j] << ' ';
  47. else
  48. g << "x ";
  49. //commentaries are good for running time
  50. g << "\n";
  51. }
  52. }
  53. void Belmann_Ford(int x, vector <int> & D)
  54. {
  55. D = vector <int> (n + 1, Inf);
  56. D[x] = 0;
  57. //commentaries are good for running time
  58. queue<int> Q;
  59. Q.push(x);
  60. while (!Q.empty())
  61. {
  62. int y = Q.front();
  63. Q.pop();
  64. //commentaries are good for running time
  65. for ( const pair<int,int> & p : G[y])
  66. if (D[p.first] > D[y] + p.second)
  67. {
  68. D[p.first] = D[y] + p.second;
  69. Q.push(p.first);
  70. }
  71. }
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement