① Floyd
Multi-source shortest
#include <cstdio> #include <iostream> #include <algorithm> #include <cstring> #include <string> #include <stack> #include <queue> #include <cmath> #define ll long long #define pi 3.1415927 #define INF 0x3f3f3f3f using namespace std; int dis[1005][1005],n; void floyd (int n) { int i,j,k; for(k=0; K <n-; ++ K) for (I = 0 ; I <n-; ++ I) for (J = 0 ; J <n-; ++ J) IF (DIS [I] [J]> DIS [I ] [K] + DIS [K] [J]) DIS [I] [J] = DIS [I] [K] + DIS [K] [J]; /// core floyd, the traverse one by one, to find the shortest distance } int main () { int n-, m, I, T, J, K, X, Y, P; Scanf ( " % D " , & n-); Memset (DIS, INF, the sizeof (DIS)); / / distance is initialized to the maximum value of the while (CIN X >> Y >> >> P) DIS [X] [Y]=p; for(i=0;i<n;++i) //自己到自己的距离为 0 dis[i][i]=0; floyd(n); for(i=0;i<n;++i){ for(t=0;t<n;++t) cout<<dis[i][t]<<" "; cout<<endl; } return 0; }
② dijkstra
Single-source shortest
#include <cstdio> #include <the iostream> #include <algorithm> #include <CString> #include < String > #include <Stack> #include <Queue> #include <the cmath> #define LL Long Long #define PI 3.1415927 # DEFINE INF 0x3f3f3f3f the using namespace STD; int DIS [ 1005 ], sign [ 1005 ], cost [ 1005 ] [ 1005 ]; // DIS [i] from point i to point 0 mark sign of cost [i] [j] point i distance to the point of j void the init (int n-) { // Initialization Memset (DIS, INF, the sizeof (DIS)); Memset (Sign, 0 , the sizeof (Sign)); Memset (cost, INF, the sizeof (cost)); // their distances to their zero for ( int I = 0 ; I <n-; ++ I) cost [I] [I] = 0 ; } void Dijkstra ( int n-, int S) { DIS [ 0 ] = 0 ; int I; the while ( 1) { Int F = - . 1 ; for (I = 0 ; I <n-; I ++) // through each point, to find the shortest distance from the origin to the IF (Sign [I] && (== F -! . 1 | | DIS [I] < DIS [F])) F = I; IF (== F - . 1 ) BREAK ; Sign [F] = . 1 ; for (I = 0 ; I <n-; I ++) // update the shortest distance DIS [I] = min (DIS [I], DIS [F] + cost [F] [I]); } } int main () { int n,m,i,t,j,k,x,y,p; cin>>n; init(n); while(cin>>x>>y>>p) cost[x][y]=p; dijkstra(n,0); for(i=0;i<n;++i) cout<<dis[i]<<" "; return 0; }
③ SPFA
Single-source shortest, negative edge weights may be processed