Click to enter the example shortest
I know there are three ways 1: Deep search update every time there is a smaller path, 2:dijkstra 3:floydThe first two are single source shortest path, if it is the shortest path of single source with the previous two, but if the multi-source shortest path is best to also use Floyd time complexity is relatively low. Using Floyd to find the shortest path of single source .... A little bit of time complexity, but the program is easy to implement,
How to implement 1:floyd
#include <stdio.h>#include<string.h>#include<math.h>#include<iostream>#include<algorithm>#include<queue>#include<vector>#include<Set>#include<stack>#include<string>#include<sstream>#include<map>#include<cctype>using namespacestd;#defineINF 99999999intMain () {inte[101][101]; intn,m,a,b,c,i,j,k; while(~SCANF ("%d%d", &n,&m) &&n!=0&&m!=0) { for(i=1; i<=n;i++)//Initialize each edge to the maximum value for(j=1; j<=n;j++) E[i][j]=INF; while(m--) {scanf ("%d%d%d", &a,&b,&c);//Determine edge and edge lengthe[b][a]=e[a][b]=C; } for(k=1; k<=n;k++)//Floyd core Algorithm ... { for(i=1; i<=n;i++)//all the way to let K add in try { for(j=1; j<=n;j++)//if K goes on the way from I to J, it will be easier, so let K go. { if(E[i][j]>e[i][k]+e[k][j])//determine if it will be easiere[i][j]=e[i][k]+E[k][j]; }}} printf ("%d\n"-E:1][n]); }}
2: Deep search completed. (Timed out .....) Data processing should be free of problems)
1#include <stdio.h>2#include <string.h>3#include <math.h>4#include <iostream>5#include <algorithm>6#include <queue>7#include <vector>8#include <Set>9#include <stack>Ten#include <string> One#include <sstream> A#include <map> -#include <cctype> - using namespacestd; the #defineINF 99999999 - intn,m,a[ the][ the],result; -vector<int>v[ the]; - voidDFS (intStarintdis) + { - if(dis>=result) + return; A if(star==N) at { -Result=result>dis?Dis:result; - return ; - } - for(intI=0; I<v[star].size (); i++) - { in if(a[star][v[star][i]]!=INF) - { to intw=A[star][v[star][i]]; +a[star][v[star][i]]=INF; -a[v[star][i]][star]=INF; theDFS (v[star][i],w+dis); *a[star][v[star][i]]=W; $a[v[star][i]][star]=W;Panax Notoginseng } - } the } + intMain () A { the for(intI=0;i< the; i++) + for(intj=0;j< the; j + +) -a[i][j]=INF; $ while(SCANF ("%d%d", &n,&m), (m| |m)) $ { -result=INF; - for(intI=0; i<m;i++) the { - intd,b,c;Wuyiscanf"%d%d%d",&d,&b,&c); the V[d].push_back (b); - V[b].push_back (d); Wua[d][b]=C; -a[b][d]=C; About } $Daso1,0);//from 1 to N. -printf"%d\n", result); - } -}
Some solutions to the shortest path------Examples < short circuit >