注:此文属于个人笔记,转载请注明出处。欢迎给各位提出意见。 注意的地方:priority_queue的用法,使用greater<>需要重载大于符号。 /* Dijkstra: BHeap + Linked List */ #include <iostream> #include <queue> #include <vector> #define PB push_back #define F(i,a,b) for (int i=a;i<=b;i++) #define MAXN 1002 using namespace std; class node { public: int t, d; node(int a, int b) { t=a, d=b; } bool operator > (const node& b) const { return (d>b.d); } }; priority_queue<node, vector<node>, greater<node> > pq; bool mk[MAXN]; int d[MAXN]; vector<node> lst[MAXN] ; void dijkstra(int s, int t) { //init memset(d,1, sizeof(d)); d[s]=0; pq.push( node(s, 0) ); int v; while (!mk[t]) { while ( mk[ pq.top().t ] ) pq.pop(); v=pq.top().t; mk[v]=true; if (v==t) break; vector<node>::iterator it=lst[v].begin(); while ( it!=lst[v].end() ) { int u=(*it).t; int dis=(*it).d; if (d[u]==-1 || d[v]+dis<d[u]) { d[u]=d[v]+dis; pq.push( node(u, d[u]) ); } it++; } } } int n, m, s, t; int main() { freopen ("in.txt", "r" , stdin); //freopen ("outtxt", "w", stdout); cin >> n >> m >> s >> t; int a, b ,c; F(i,1,m) { cin >> a >> b >> c; lst[a].PB( node(b, c) ); lst[b].PB( node(a, c) ); } dijkstra(s, t); cout << d[t]; return 0; } /* in.txt 6 9 1 5 1 6 14 1 3 9 1 2 7 2 3 10 3 4 11 3 6 2 2 4 15 4 5 6 5 6 9 http://en.wikipedia.org/wiki/File:Dijksta_Anim.gif output: 20 */