fork download
  1. #include <stdio.h>
  2. #include <iostream>
  3. #include <vector>
  4. #include <queue>
  5.  
  6. using namespace std;
  7.  
  8. #define inf 100000000
  9.  
  10. int main()
  11. {
  12. vector<int> V[100];
  13. int cost[100][100];
  14. queue<int> Q;
  15. int v, e;
  16.  
  17. scanf("%d %d", &v, &e);
  18. for (int a = 0; a < e; a++)
  19. {
  20. int m, n, z;
  21. scanf("%d %d %d", &m, &n, &z);
  22. cost[m][n] = z;
  23. V[m].push_back(n);
  24. }
  25.  
  26. int s, d;
  27. //cout << "Enter Source:";
  28. scanf("%d", &s);
  29. //cout << "Enter Destination:";
  30. scanf("%d", &d);
  31.  
  32. int dis[100] = {inf};
  33. int color[100] = {0};
  34. int parent[100];
  35.  
  36. for (int i = 0; i < 100; ++i)
  37. dis[i] = inf;
  38.  
  39. dis[s] = 0;
  40. dis[d] = inf + 1;
  41. int source;
  42. source = s;
  43. Q.push(s);
  44. //for (int c = 0;c < V[d].size(); c++) //I dont need to visit nodes from destination
  45. //{
  46. // color[V[d][c]] = 2;
  47. //}
  48.  
  49. do {
  50. if (source == d)
  51. break;
  52. for (int b = 0; b < V[source].size(); b++)
  53. {
  54. int adj = V[source][b];
  55. if (color[adj] != 2)
  56. {
  57. Q.push(adj);
  58. color[adj] = 1;
  59. }
  60.  
  61. if (dis[adj] > (dis[source] + cost[source][adj]))
  62. {
  63. dis[adj] = dis[source] + cost[source][adj];
  64. parent[adj] = source;
  65. }
  66. if (dis[adj] >= dis[d] && adj != d) //If I detect any path already crossing limit updated by loop I can ignore it
  67. {
  68. color[adj] = 2;
  69. }
  70. }
  71. color[source] = 2;
  72. Q.pop();
  73. source = Q.front();
  74. } while (!Q.empty());
  75.  
  76. cout << "The minimum distance is " << dis[d] << ".\n";
  77. return 0;
  78. }
Success #stdin #stdout 0s 2824KB
stdin
9 15
0 1 10
0 3 15
1 4 20
2 1 13
2 5 22
2 6 17
3 4 19
3 8 12
4 2 21
4 5 16
5 6 11
5 7 24
5 8 23
7 6 14
7 8 18
0 2
stdout
The minimum distance is 51.