/* Mail to : miyubai@gamil.com My Blog : www.baiyun.me Author By : MiYu Test : 1 Complier : g++ mingw32-3.4.2 Program : HDU_2544 Doc Name : 最短路 */ //#pragma warning( disable:4789 ) #include <iostream> #include <fstream> #include <sstream> #include <algorithm> #include <string> #include <set> #include <map> #include <utility> #include <queue> #include <stack> #include <list> #include <vector> #include <cstdio> #include <cstdlib> #include <cstring> #include <cmath> #include <ctime> using namespace std; void Debug () { #ifdef LOCAL freopen ( "1.in", "r", stdin ); freopen ( "1.out", "w", stdout ); #endif } void pause () { #ifdef LOCAL system ( "pause" ); #endif } inline bool read(int &num) { char in;bool IsN=false; in=getchar(); if(in==EOF) return false; while(in!='-'&&(in<'0'||in>'9')) in=getchar(); if(in=='-'){ IsN=true;num=0;} else num=in-'0'; while(in=getchar(),in>='0'&&in<='9') num*=10,num+=in-'0'; if(IsN) num=-num; return true; } int N, M, x, y, z, res[110]; struct Sp { int s, val; Sp ( int x = 0, int y = 0 ): s( x ), val( y ) {} bool operator < ( const Sp& t ) const { if ( val != t.val ) return val > t.val; return s > t.s; } }sp; vector < Sp > vec[110];//用STL中的向量来表示其相邻节点;就是一个链接表,比邻接矩阵节省空间 int Dijkstra ( ) { memset ( res, 0x7f, sizeof ( res ) );//res中保存的是第i个节点到起始点的距离; res[1] = 0;//起点到起点距离为0; priority_queue < Sp > que;//定义一个优先队列; que.push ( Sp ( 1, 0 ) ); while ( !que.empty () ) { sp = que.top (); que.pop (); int pos = sp.s, val = sp.val; if ( pos == N ) return val; for ( int i = 0; i < vec[pos].size(); ++ i ) { if ( res[ vec[pos][i].s ] > res[pos] + vec[pos][i].val ) { res[ vec[pos][i].s ] = res[pos] + vec[pos][i].val; que.push ( Sp ( vec[pos][i].s, res[ vec[pos][i].s ] ) ); } } } return -1; } int main () { //Debug (); while ( read ( N ), read ( M ), N | M ) {//成都有n个路口,m条路。 for ( int i = 1; i <= N; ++ i ) vec[i].clear ();//每次读取数据,把向量清空; for ( int i = 0; i < M; ++ i ) { read ( x ), read ( y ), read ( z );//x,y之间的权值是z; vec[x].push_back ( Sp ( y, z ) ) ; vec[y].push_back ( Sp ( x, z ) ) ; } printf ( "%d/n", Dijkstra () ); } pause (); return 0; } 这个代码我是从别人那拷贝过来的。加了一些自己的注释,感觉真的很完美。