簡體   English   中英

這個 dijkstra 算法實現中是否有任何錯誤?

[英]Is there any bug in this dijkstra algorithm implementation?

我剛剛學習了 Dijkstra 的算法並解決了一些問題,我正在嘗試解決這個http://codeforces.com/problemset/problem/20/C問題,但我在測試用例 31 中得到了錯誤的答案。我不明白為什么會這樣得到錯誤的答案。 首先,它在測試用例 31 上超出了內存限制。但是當我將 int 更改為 long long of d[] arrray 時,它得到了錯誤的答案。 請讓我知道為什么它得到錯誤的答案。

我的代碼:

#include <bits/stdc++.h>

using namespace std;

typedef struct data Data;

struct data{
    long long int city,dis;
    bool operator < (const data & p) const{
        return dis > p.dis;
    }
};

#define tr(niloy,it) for(auto it = niloy.rbegin(); it != niloy.rend(); it++)

void dijkstra(const vector <long long int>  edge[],const vector <long long int>  cost[], int source, int destination,int n,int m)
{
    long long int d[n];
    bool nodes[n];
    vector <int> parent(n,-1);
    for(int i = 0; i < n; i++){
        d[i] = INT_MAX;
        parent[i] = -1;
        nodes[i] = false;
    }
    priority_queue <Data> p;
    Data u,v;
    u.city = 0;
    u.dis = 0;
    p.push(u);
    d[source] = 0;
    while(!p.empty()){
        u = p.top();
        p.pop();
        long long int ucost = d[u.city];
        if(u.city == destination)break;
        if(nodes[u.city])continue;
        nodes[u.city] = true;
        //cout << edge[u.city].size() << endl;
        for(int i = 0; i < edge[u.city].size(); i++){
            v.dis = ucost + cost[u.city][i];
            v.city = edge[u.city][i];
            if(d[v.city] > v.dis){
                ///cout << v.city << " " << u.city << endl;
                parent[v.city] = u.city;
                d[v.city] = v.dis;
                p.push(v);
            }
        }
    }
    vector<int> niloy;
    ///cout << d[destination] << endl;
    if(parent[destination] != -1){
        niloy.push_back(n);
        while(destination != 0){
            niloy.push_back(parent[destination]+1);
            destination = parent[destination];
        }
        tr(niloy,it)cout << *it << " " ;
    }else{
        ///cout << d[destination] << endl;
        cout << -1 << endl;
    }

}

int main()
{
    int n,m;
    cin>> n >> m;
    vector <long long int> edge[n],cost[n];

    int a,b,c;

    for(int i = 0; i < m; i++){
        cin >> a >> b >> c;
        if(a == b)continue;
        edge[a-1].push_back(b-1);
        cost[a-1].push_back(c);
        edge[b-1].push_back(a-1);
        cost[b-1].push_back(c);
    }
    //cout << edge[0][0] << endl;
    dijkstra(edge,cost,0,n-1,n,m);

    return 0;
}

算法實現對我來說看起來是正確的,唯一似乎錯誤的是這一行:

d[i] = INT_MAX;

如果編譯器使用 32 位整數,則INT_MAX將是 2^32(接近 10^9),而如果您有一個線性圖,則最佳解決方案的最大可能實際長度可能會超過:1 -> 2 -> 3 - > ... -> n 並且每條邊的長度為 10^6。 在這種情況下,最短路徑將接近 10^11,這大於INT_MAX ,這意味着d數組的初始值並不是真正的“無限”,因為 dijkstra 的算法要求。

將初始值更改為更高的數字應該可以解決此問題(10^12 應該就足夠了,但您也可以使用LLONG_MAX ):

d[i] = 1000000000000; // 10^12

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM