最短路
Time Limit: 5000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 33690 Accepted Submission(s): 14633
Problem Description
在每年的校赛里,所有进入决赛的同学都会获得一件很漂亮的t-shirt。但是每当我们的工作人员把上百件的衣服从商店运回到赛场的时候,却是非常累的!所以现在他们想要寻找最短的从商店到赛场的路线,你可以帮助他们吗?
Input
输入包括多组数据。每组数据第一行是两个整数N、M(N<=100,M<=10000),N表示成都的大街上有几个路口,标号为1的路口是商店所在地,标号为N的路口是赛场所在地,M则表示在成都有几条路。N=M=0表示输入结束。接下来M行,每行包括3个整数A,B,C(1<=A,B<=N,1<=C<=1000),表示在路口A与路口B之间有一条路,我们的工作人员需要C分钟的时间走过这条路。
输入保证至少存在1条商店到赛场的路线。
输入保证至少存在1条商店到赛场的路线。
Output
对于每组输入,输出一行,表示工作人员从商店走到赛场的最短时间
Sample Input
2 1 1 2 3 3 3 1 2 5 2 3 5 3 1 2 0 0
Sample Output
3 2
//dijkstra算法 #include <iostream> #include <algorithm> #include <string> #include <cstdio> #include <cstring> #include <cstdlib> #include <cmath> #include <vector> #include<queue> #include<stack> #include<map> using namespace std; #define lson ((root<<1)+1) #define rson ((root<<1)+2) #define MID ((l+r)>>1) typedef long long ll; typedef pair<int,int> P; #define For(i,t,n) for(int i=(t);i<(n);i++) const int maxn=800; const int base=1000; const int inf=999999; int n,m; int cost[maxn][maxn]; bool used[maxn]; int d[maxn]; void dij(int s) { fill(d,d+n+1,inf); d[s]=0; memset(used,0,sizeof(used)); while(1) { int v=-1; for(int u=1; u<=n; u++) if(!used[u]&&(v==-1||d[u]<d[v]))v=u; if(v==-1)break; used[v]=1; for(int u=1; u<=n; u++) { d[u]=min(d[u],d[v]+cost[v][u]); } } } int main() { int i,j,k; while(cin>>n>>m,n,m) { for(i=1; i<=n; i++) for(j=1; j<=n; j++) cost[i][j]=inf; for(i=1; i<=m; i++) { int s,e,t; cin>>s>>e>>t; if(t<cost[s][e]) { cost[s][e]=t; cost[e][s]=t; } } dij(1); cout<<d[n]<<endl; } return 0; }
bellman_ford算法
#include <iostream> #include <algorithm> #include <string> #include <cstdio> #include <cstring> #include <cstdlib> #include <cmath> #include <vector> #include<queue> #include<stack> #include<map> using namespace std; #define lson ((root<<1)+1) #define rson ((root<<1)+2) #define MID ((l+r)>>1) typedef long long ll; typedef pair<int,int> P; #define For(i,t,n) for(int i=(t);i<(n);i++) const int maxn=800001; const int base=1000; const int inf=999999; struct edge{int from,to,cost;}; edge es[maxn]; int d[maxn]; int n,m; void bellman(int s) { fill(d,d+1+n,inf); d[s]=0; while(1) { bool ok=0; for(int i=1;i<=2*m;i++) { edge e=es[i]; if(d[e.from]!=inf&&d[e.to]>d[e.from]+e.cost) { d[e.to]=d[e.from]+e.cost; ok=1; } } if(ok==0)break; } } int main() { int i,j,k,t; while(scanf("%d%d",&n,&m),n,m) { for(i=1;i<=m*2;i+=2) { scanf("%d%d%d",&es[i].from,&es[i].to,&es[i].cost); es[i+1].from=es[i].to; es[i+1].to=es[i].from; es[i+1].cost=es[i].cost; } bellman(1); printf("%d\n",d[n]); } return 0; }