题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1874
dijkstra算法模板题1A
#include<iostream> #include<string> #include<cstdio> #include<cstring> #include<map> #include<queue> #include<cmath> #include<stack> #include<set> #include<vector> #include<algorithm> #define LL long long #define inf 1<<29 #define s(a) scanf("%d",&a) #define CL(a,b) memset(a,b,sizeof(a)) using namespace std; const int N=205; int n,m,a,b,c; int Map[N][N]; int dist[N]; bool vis[N]; void dijkstra() { CL(vis,false); for(int i=1;i<=n;i++) dist[i]=Map[a][i]; vis[a]=true; while(1){ int v=-1; for(int u=1;u<=n;u++){ if(!vis[u]&&(v==-1||dist[u]<dist[v])) v=u; } if(v==-1) break; vis[v]=true; for(int u=1;u<=n;u++){ dist[u]=min(dist[u],dist[v]+Map[v][u]); } } } int main() { int t; while(~scanf("%d%d",&n,&m)){ n++; for(int i=1;i<=n;i++){ for(int j=1;j<=n;j++) Map[i][j]=inf; Map[i][i]=0; } for(int i=0;i<m;i++){ scanf("%d%d%d",&a,&b,&c);a++;b++; if(Map[a][b]>c) Map[a][b]=Map[b][a]=c; } scanf("%d%d",&a,&b);a++;b++; dijkstra(); if(dist[b]==inf) printf("-1\n"); else printf("%d\n",dist[b]); } return 0; }
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/wlxsq/article/details/48101965