GastonFontenla

FloydWarshall

Aug 11th, 2019
229
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.64 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <queue>
  4.  
  5. using namespace std;
  6.  
  7. #define INF 1e9
  8.  
  9. int D[600][600]; ///Matriz de adyacencia
  10. int N; ///La cantidad de nodos
  11.  
  12. void floydWarshall()
  13. {
  14.     ///Para cada par de nodos i, j
  15.     ///Qué es mejor, la distancia que tengo calculada
  16.     ///o ir de i->k y luego de k->j ?
  17.  
  18.     for(int k=1; k<=N; k++)
  19.         for(int i=1; i<=N; i++)
  20.             for(int j=1; j<=N; j++)
  21.                 D[i][j] = min(D[i][j], D[i][k]+D[k][j]);
  22. }
  23.  
  24. int main()
  25. {
  26.     int cantAristas;
  27.     int a, b, c;
  28.     cin >> N >> cantAristas;
  29.  
  30.     ///Llenar inicialmente todas las distancias con infinito
  31.     ///En D[i][i] decidimos que la distancia es cero
  32.     ///(o sea, para llegar de i hasta i, no te movés, cero distancia)
  33.  
  34.     for(int i=1; i<=N; i++)
  35.         for(int j=1; j<=N; j++)
  36.             D[i][j] = INF;
  37.  
  38.     for(int i=1; i<=N; i++)
  39.         D[i][i] = 0;
  40.  
  41.     for(int i=0; i<cantAristas; i++)
  42.     {
  43.         cin >> a >> b >> c;
  44.         D[a][b] = c;
  45.         D[b][a] = c;
  46.     }
  47.  
  48.     /**
  49.     Floyd Warshall es un algoritmo que calcula
  50.     la distancia entre cada par de nodos
  51.     en tiempo O(N^3), lo que no es rápido, pero
  52.     que en algunas circunstancias es suficiente
  53.     **/
  54.  
  55.     floydWarshall();
  56.  
  57.     for(int i=1; i<=N; i++)
  58.     {
  59.         for(int j=1; j<=N; j++)
  60.         {
  61.             cout << D[i][j] << " ";
  62.         }
  63.         cout << endl;
  64.     }
  65.  
  66.     return 0;
  67. }
  68.  
  69. /**
  70. Ejemplo de input:
  71. 6 9
  72. 1 2 7
  73. 1 3 9
  74. 1 6 14
  75. 2 3 10
  76. 2 4 15
  77. 3 4 11
  78. 3 6 2
  79. 4 5 6
  80. 5 6 9
  81.  
  82. Output correcto:
  83. 0 7 9 20 20 11
  84. 7 0 10 15 21 12
  85. 9 10 0 11 11 2
  86. 20 15 11 0 6 13
  87. 20 21 11 6 0 9
  88. 11 12 2 13 9 0
  89. **/
Advertisement
Add Comment
Please, Sign In to add comment