Dijkstra求调试

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

loss_of_time @ 2022-11-23 18:51:37

#include <limits.h>
#include <queue>
#include <stdio.h>
#include <string.h>
#include <vector>
using namespace std;

struct Edge {
    int to, dis;
};
struct Node {
    int id, dis;
    bool operator<(const Node &a) const { return this->dis > a.dis; }
};
const int maxn = 100005;
vector<Edge> G[maxn];
int dis[maxn], u[maxn] = {0};
int n, m, s;

inline void init() {
    scanf("%d%d%d", &n, &m, &s);
    int a, b, d;
    Edge tmp;
    for (int i = 1; i <= n; ++i) {
        dis[i] = INT_MAX;
    }
    for (int i = 1; i <= m; ++i) {
        scanf("%d%d%d", &a, &b, &d);
        tmp.to = b;
        tmp.dis = d;
        G[a].push_back(tmp);
        tmp.to = a;
        G[b].push_back(tmp);
    }
}

inline void dijkstra(int a) {
    priority_queue<Node> pq;
    Node temp;
    int id, l, to, d;
    temp.id = a;
    temp.dis = 0;
    dis[a] = 0;
    pq.push(temp);
    while (!pq.empty()) {
        id = pq.top().id;
        l = pq.top().dis;
        pq.pop();
        if (u[id])
            continue;
        u[id] = 1;
        for (int i = 0; i < G[id].size(); ++i) {
            to = G[id][i].to;
            d = G[id][i].dis;
            if (!u[to] && l + d < dis[to]) {
                dis[to] = l + d;
                temp.id = to;
                temp.dis = dis[to];
                pq.push(temp);
            }
        }
    }
}

int main() {

    init();
    dijkstra(s);
    for (int i = 1; i <= n; ++i) {
        printf("%d ", dis[i]);
    }
}

六个实例对三个,实在不知到哪里错了


by bbjr @ 2022-11-23 19:04:45

题目是单向边,您连的这是双向边


by loss_of_time @ 2022-11-23 19:22:06

@bbxz 问题解决了,感谢


|