FloydWarshall.cpp 894 B

1234567891011121314151617181920212223242526272829
  1. #include <iostream>
  2. #include <cstdio>
  3. #define INF 0x7fffffff
  4. using namespace std;
  5. const int maxn = 101;
  6. int a[maxn][maxn]; // matrice adjacente
  7. int pre[maxn][maxn]; // pre[i][j] = the previous node of j in the path from i to j.
  8. int dist[maxn][maxn];
  9. int n;
  10. //O(n^3)
  11. void floyd() {
  12. //initialisation
  13. for(int i = 1; i <= n; i++)
  14. for(int j = 1;j <= n; j++)
  15. if (a[i][j]) {
  16. dist[i][j] = a[i][j]; pre[i][j] = i;
  17. }
  18. else {
  19. dist[i][j] = INF; pre[i][j] = -1;
  20. }
  21. //floyd
  22. for(int k = 1; k <= n; k++)
  23. for(int i = 1; i <= n; i++)
  24. for(int j = 1;j <= n ; j++)
  25. if(dist[i][k] != INF && dist[k][j] != INF && dist[i][k] + dist[k][j] < dist[i][j]) {
  26. dist[i][j] = dist[i][k] + dist[k][j];
  27. pre[i][j] = pre[k][j];
  28. }
  29. }