标签:
Input
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算法
可以看看这位的博客 http://www.cnblogs.com/biyeymyhjob/archive/2012/07/31/2615833.html
#include <iostream> #include <cstdio> #include <algorithm> #include <cstring> #include <queue> #include <cmath> #include <map> #include <stack> #include <vector> #define lson l,m,rt<<1 #define rson m+1,r,rt<<1|1 using namespace std; const int MX=110; const int INF=0x3f3f3f3f; int n,Map[MX][MX],dist[MX]; void init(){ for (int i=1;i<=n;i++) for (int j=1;j<=n;j++) Map[i][j]=INF; } void dijkstra(int v0){ bool S[MX]; for (int i=1;i<=n;i++){ //初始化 dist[i]=Map[v0][i]; S[i]=false; } dist[v0]=0; S[v0]=true; for (int i=2;i<=n;i++){ int temp=INF; int u=v0; for (int j=1;j<=n;j++) //找出距离v0最小的点 if (!S[j]&&dist[j]<temp){ u=j; temp=dist[j]; } S[u]=true; for (int j=1;j<=n;j++) //判断 if (!S[j]&&dist[u]+Map[u][j]<dist[j]) dist[j]=dist[u]+Map[u][j]; } } int main() { int m; while (~scanf ("%d %d",&n,&m)){ if (n==0&m==0) break; init(); while (m--){ int u,v,w; scanf ("%d %d %d",&u,&v,&w); if (Map[u][v]==INF){ Map[u][v]=w; Map[v][u]=w; } } dijkstra(1); printf ("%d\n",dist[n]); //如果dist[n]等于INF,说明1到n之间不可达 } return 0; }
标签:
原文地址:http://www.cnblogs.com/yusize/p/5750288.html