最短路问题
单源最短路:
Bellman-Ford 可以解决存在负边问题,复杂度:O(|边||点|)
Dijkstra 不能解决负边 邻接矩阵、邻接表复杂度:O(|点|^2),优先队列复杂度:O(|边|)
任意两点间的最短路问题:
Floyd-Warshall 可以解决负边问题,复杂度O(|点|^3)
路径还原:~~
1. POJ 2387(模板题)
题目大意:有N个点,给出从A点到B点的距离(A和B可以互相到达),问从1点到N点的最短距离.
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include<cstdio> 2 using namespace std; 3 #define MAX_E 2005 4 #define INF 1<<30 5 struct edge 6 { 7 int from,to,cost; 8 }; 9 edge es[MAX_E]; 10 int N,E;///E 边数,N 目标点 11 void shortest_path() 12 { 13 int d[1002]; 14 for(int i=2; i<=N; ++i)d[i]=INF; 15 d[1]=0; 16 for(int i=1; i<=N; i++) 17 { 18 for(int j=1; j<=E; j++) 19 { 20 if(d[es[j].from]>es[j].cost+d[es[j].to]) d[es[j].from]=es[j].cost+d[es[j].to]; 21 if(d[es[j].to]>es[j].cost+d[es[j].from]) d[es[j].to]=es[j].cost+d[es[j].from]; 22 } 23 } 24 printf("%d\n",d[N]); 25 } 26 int main() 27 { 28 while(scanf("%d%d",&E,&N)!=EOF) 29 { 30 for(int i=1; i<=E; i++) 31 { 32 scanf("%d%d%d",&es[i].from,&es[i].to,&es[i].cost); 33 } 34 shortest_path(); 35 } 36 return 0; 37 }