【问题标题】:Wrong output in DijkstraDijkstra 中的错误输出
【发布时间】:2020-01-06 10:52:23
【问题描述】:

今天我正在解决一个问题,我们必须找到 0 和 n-1 之间的距离 这是我的代码,它只是输出我之前初始化它的-INF,它甚至没有改变(这里我使用的是邻接矩阵而不是列表) 这是我的代码:


#include <bits/stdc++.h>
using namespace std;
typedef long long int ll ;
#define INF LLONG_MAX

vector<bool> visited(100);
vector<ll> dist(100);
priority_queue<pair<ll,ll>> q;
ll n,m,a,b,c;
vector<vector<ll>> adj(100 , vector<ll> (100));

void dijkstra(ll s) {

    for (ll i = 0; i < n; i++) {
        dist[i] = -INF;
        visited[i] = false;
    }

    dist[s] = 0;
    q.push({0, s});

    while (!q.empty()) {

        ll y = q.top().second;
        q.pop();

        if (visited[y]) continue;
        visited[y] = true;

        for (ll j = 0; j < n; j++) {

            if (adj[y][j] == 0) continue;

            if (dist[y] + adj[y][j] < dist[j]) {
                dist[j] = dist[y] + adj[y][j];
                q.push(make_pair(-dist[j], j));
            }
        }
    }
}

int main() {


    cin >> n >> m;
    for(ll i = 0; i < m; i++){
        cin >> a >> b >> c;
        adj[a-1][b-1] = c;
        adj[b-1][a-1] = c;
    }

    dijkstra(0);
    ll distan = dist[n-1];

    cout << distan;

    return 0;
}

Input is this : 

5 7
2 1 5
1 3 1
3 2 8
3 5 7
3 4 3
2 4 7
4 5 2

Output is : 6 

请让我知道我应该在我的代码中进行哪些更改 谢谢!!

【问题讨论】:

  • 你应该使用像 gdb 这样的调试器来调试你的代码
  • 我在 IDE 中调试但找不到错误,这就是我在这里提出问题的原因
  • 您应该将实际值与预期值进行比较。您发现最终结果有所不同。现在您应该调试代码并找出这种差异的来源。
  • 你为什么要推-dist
  • 因为我们需要距离升序和优先队列降序排序

标签: c++ graph dijkstra


【解决方案1】:

知道了,我应该做 INF 而不是 -INF :(

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多