dijkstra堆优化求助!

P4779 【模板】单源最短路径(标准版)

zuoqirun @ 2023-12-02 21:54:09

#include <bits/stdc++.h>
using namespace std;
const int maxm = 2e5 + 10;
const int maxn = 1e5 + 10;
const int inf = 0x7fffffff;
struct Edge {
    int v, c, next;
}a[maxn];
struct Node {
    int u, dis;
    bool operator<(const Node& n) const {
        return dis > n.dis;
    }
};
int h[maxm], n, m, s, tot, dis[maxn];
bool vis[maxn];
priority_queue<Node> que;
void addedge(int u, int v, int c) {
    a[++tot].v = v; a[tot].c = c;
    a[tot].next = h[u]; h[u] = tot;
}
void dijkstra() {
    for (int i = 1; i <= n; i++) {
        dis[i] = inf;
    }
    dis[s] = 0;
    que.push({s, 0});
    while (que.size()) {
        int u = que.top().u; que.pop();
        if (vis[u]) continue;
        vis[u] = 1;
        for (int i = h[u]; i; i = a[i].next) {
            int v = a[i].v, c = a[i].c;
            if (dis[v] > dis[u] + c) {
                dis[v] = dis[u] + c;
                que.push({v, dis[v]});
            }
        }
    }
}
int main(){
    cin >> n >> m >> s;
    for (int i = 1; i <= m; i++) {
        int u, v, w;
        cin >> u >> v >> w;
        addedge(u, v, w);
    }
    dijkstra();
    for (int i = 1; i <= n; i++) {
        cout << dis[i] << " ";
    }
    return 0;
}

16分(1, 3, 4, 5, 6测试点RE)


by Eason_wu @ 2023-12-05 22:26:16

你好!

struct Edge {
    int v, c, next;
}a[maxn];

应改为

struct Edge {
    int v, c, next;
}a[maxm];

by zuoqirun @ 2023-12-09 19:13:29

@Eason_wu 谢谢大佬,没注意,出了个小错误T_T


|