标签:while har dijkstra sdi namespace class space 最短路 col
最短路,即第1短路有很多种求法,SPFA,Dijkstra等,但第k短路怎么求呢?其实也是基于Dijkstra;因为Dijkstra用的是堆优化,这样保证每次弹出来的都是最小值,只是求最短路只是弹出一次就返回了,我们可以用Dijkstra弹出k个距离后再返回,这样根据弹出的先后顺序能够求出1~k短路
#include <bits/stdc++.h> using namespace std; typedef long long ll; const int INF = 0x3f3f3f3f; const int MAXN = 5e5 + 100; const int MAXM = 3e3 + 10; inline int read() { int x = 0, ff = 1; char ch = getchar(); while(!isdigit(ch)) { if(ch == ‘-‘) ff = -1; ch = getchar(); } while(isdigit(ch)) { x = (x << 1) + (x << 3) + (ch ^ 48); ch = getchar(); } return x * ff; } inline void write(ll x) { if(x < 0) putchar(‘-‘), x = -x; if(x > 9) write(x / 10); putchar(x % 10 + ‘0‘); } int n, m, k, v; ll ans, dist[110]; int lin[MAXN], tot = 0; struct edge { int y, v, next; }e[MAXN]; inline void add(int xx, int yy, int vv) { e[++tot].y = yy; e[tot].v = vv; e[tot].next = lin[xx]; lin[xx] = tot; } void Dijkstra() { priority_queue < pair < int , int > > q; q.push(make_pair(0, 1)); while(!q.empty()) { int x = q.top().second; int d = -q.top().first; q.pop(); if(x == n) { dist[++v] = d; if(v == k + 1) return ; } for(int i = lin[x], y; i; i = e[i].next) { y = e[i].y; ans = d + e[i].v; q.push(make_pair(-ans, y)); } } } int main() { memset(dist, -1, sizeof(dist)); n = read(); m = read(); k = read(); for(int i = 1; i <= m; ++i) { int x,y,v; x = read(); y = read(); v = read(); add(x, y, v); } Dijkstra(); for(int i = 1; i <= k; ++i) { write(dist[i]); putchar(‘\n‘); } return 0; }
标签:while har dijkstra sdi namespace class space 最短路 col
原文地址:https://www.cnblogs.com/AK-ls/p/10614203.html