#include<cstdio> #include<cstring> #include<cmath> #include<algorithm> #include<iostream> #define inf 999999999 #define maxn 105 using namespace std; int g[maxn][maxn]; int dist[maxn]; int vis[maxn]; int n,m; void dijkstra(int st){ int i,j,mindis,u; memset(vis,0,sizeof(vis)); for(i=1;i<=n;i++){ dist[i]=g[st][i]; } vis[st]=1; for(i=1;i<=n;i++){ mindis=inf; u=-1; for(j=1;j<=n;j++){ if(!vis[j]&&mindis>dist[j]){ mindis=dist[j]; u=j; } } if(u==-1)break; vis[u]=1; for(j=1;j<=n;j++){ if(!vis[j]&&dist[j]>dist[u]+g[u][j]){ dist[j]=dist[u]+g[u][j]; } } } } int main(){ int i,j,t; while(scanf("%d%d",&n,&m)!=EOF){ if(!n&&!m)break; for(i=1;i<=n;i++){ for(j=1;j<=n;j++){ if(i==j)g[i][j]=0; else g[i][j]=inf; } dist[i]=inf; } for(i=0;i<m;i++){ int a,b,x; scanf("%d%d%d",&a,&b,&x); if(g[a][b]>x)g[a][b]=g[b][a]=x; } dijkstra(1); if(dist[n]==inf)printf("-1\n"); else printf("%d\n",dist[n]); } return 0; }
hdu2544 最短路
最新推荐文章于 2020-08-08 21:25:35 发布