Basic idea: At first, only the 1th vertices are allowed to relay, then only the 1 and 2nd vertices are allowed to relay ... The shortest path between any two points is allowed through all vertices of the 1~n number. It is summed up in one sentence: from vertex i to the J Vertex only passes through the shortest path of the former K point. Time complexity O (n^3).
Code:
#include <stdio.h> #include <string.h> #include <stdlib.h> #define INF 999999int Main (int argc, Char Const *argv[]) {int k, I, J, N, M;int Q1, Q2, Q3;int e[10][10];scanf ("%d%d", &n, &m); for (i = 1; I <= n; ++i) {fo R (j = 1; j <= N; ++j) {if (i = = j) {E[i][j] = 0;} ELSE{E[I][J] = INF;}}} for (i = 1; I <= m; ++i) {scanf ("%d%d%d", &q1, &Q2, &q3); e[q1][q2] = Q3;} for (k = 1; k <= N; ++k)/ //Floyd-warshall algorithm core statement {for (i = 1; I <= n; ++i) {for (j = 1; j <= N; ++j) {if (E[i][j] > E[i][k] + e[k][j]) {e[i][j] = E[i][k] + e[k][j];}}} for (i = 1; I <= n; ++i) {for (j = 1; j <= N; ++j) {printf ("%5d", E[i][j]);} printf ("\ n");} System ("pause"); return 0;}
The Floyd-warshall algorithm cannot solve a graph with a "negative weight loop" or a "negative weight loop" because there is no shortest path to a graph with a "negative weight loop".
This does not exist the shortest path from vertex number 1th to vertex 3rd, because 1->2->3->1->2->3->1-> 1->2->3 such a path, each round 1->2->3 such a ring, the shortest path will be reduced by 1, never find the shortest path.
Only the five elements of the algorithm--floyd-warshall