图论-Dijkstra(堆优化)模板
测试题目:NKOJ1120 NKOJ3639
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <stdio.h> 2 #include <vector> 3 #include <queue> 4 5 using namespace std; 6 7 typedef long long LL; 8 9 const int _N = 420000; 10 const long long INF = 99999999999999LL; 11 12 LL n, m; 13 LL dis[_N]; 14 15 struct node { 16 LL v, w; 17 node(const LL &_v, const LL &_w): 18 v(_v), w(_w) {} 19 }; 20 21 struct strdis { 22 LL v, dis; 23 strdis(const LL &_v, const LL &_dis): 24 v(_v), dis(_dis) {} 25 bool operator < (const strdis &tmp) const 26 { 27 return this->dis > tmp.dis; 28 } 29 }; 30 31 vector<node> G[_N]; 32 priority_queue<strdis> Q; 33 34 void Dijkstra(int beg) 35 { 36 LL i; 37 for (i = 1; i <= n; ++i) dis[i] = INF; 38 dis[beg] = 0; 39 while (!Q.empty()) Q.pop(); 40 Q.push(strdis(beg, dis[beg])); 41 while (!Q.empty()) { 42 LL p = Q.top().v; 43 vector<node>::iterator it; 44 if (Q.top().dis != dis[p]) { Q.pop(); continue; } 45 for (it = G[p].begin(); it != G[p].end(); ++it) { 46 if (dis[it->v] <= dis[p] + it->w) continue; 47 dis[it->v] = dis[p] + it->w; 48 Q.push(strdis(it->v, dis[it->v])); 49 } 50 Q.pop(); 51 } 52 return ; 53 } 54 55 int main() 56 { 57 LL i, t1, t2, t3; 58 scanf("%lld%lld", &n, &m); 59 for (i = 1; i <= m; ++i) { 60 scanf("%lld%lld%lld", &t1, &t2, &t3); 61 G[t1].push_back(node(t2, t3)); 62 } 63 scanf("%lld%lld", &t1, &t2); 64 Dijkstra(t1); 65 printf("%lld\n", dis[t2]); 66 return 0; 67 }