堆优化版dijkstra算法

堆优化的dijkstra算法用于稀疏图,也就是m~n级别的图,算法时间复杂度O(mlog(n))

vis数组的用处:堆优化是按照距离来进行排序,可能会出现距离已经被优化的点,和原先没被优化的距离同时进入了堆,也就是堆内的元素数实际上不等于顶点数,而是边数,vis就是为了处理上述可能被重复更新的点

#pragma optimize(2)
#include
#include
#define endl '\n'
#define int int64_t
using namespace std;
const int  N = 1e5 + 10;
struct edge { int v, w; };
vectore[N];
int d[N],vis[N],m,n,s;
priority_queue, vector>, greater>>q;
void dijkstra(int s) {
    for (int i = 0; i <= n; ++i) d[i] = INT_MAX;
    d[s] = 0; q.push({ 0,s });
    while (q.size()) {
         int u = q.top().second; q.pop();
         if (vis[u]) continue;
         vis[u] = 1;
         for (auto k : e[u]) {
             if (d[k.v] > d[u] + k.w) {
                   d[k.v] = d[u] + k.w;
                   q.push({ d[k.v],k.v });
               }
         }
    }
}
signed main() {
    ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
    cin >> n >> m >> s;
    for (int i = 1; i <= m; ++i) {
         int a, b, c; cin >> a >> b >> c;
         e[a].push_back({ b,c });
    }
    dijkstra(s);
    for (int i = 1; i <= n; ++i) cout << d[i] << " ";
    return 0;
}

你可能感兴趣的:(算法)