Dijkstra算法问题

4
在下面的代码中:
#define MAX_VERTICES 260000

#include <fstream>
#include <vector>
#include <queue>
#define endl '\n'
using namespace std;

struct edge {
    int dest;
    int length;
};

bool operator< (edge e1, edge e2) {
    return e1.length > e2.length;
}

int C, P, P0, P1, P2;
vector<edge> edges[MAX_VERTICES];
int best1[MAX_VERTICES];
int best2[MAX_VERTICES];

void dijkstra (int start, int* best) {
    for (int i = 0; i < P; i++) best[i] = -1;
    best[start] = 0;
    priority_queue<edge> pq;
    edge first = { start, 0 };
    pq.push(first);
    while (!pq.empty()) {
        edge next = pq.top();
        pq.pop();
        if (next.length != best[next.dest]) continue;
        for (vector<edge>::iterator i = edges[next.dest].begin(); i != edges[next.dest].end(); i++) {
            if (best[i->dest] == -1 || next.length + i->length < best[i->dest]) {
                best[i->dest] = next.length + i->length;
                edge e = { i->dest, next.length+i->length };
                pq.push(e);
            }
        }
    }
}

int main () {
    ifstream inp("apple.in");
    ofstream outp("apple.out");

    inp >> C >> P >> P0 >> P1 >> P2;
    P0--, P1--, P2--;
    for (int i = 0; i < C; i++) {
        int a, b;
        int l;
        inp >> a >> b >> l;
        a--, b--;
        edge e = { b, l };
        edges[a].push_back(e);
        e.dest = a;
        edges[b].push_back(e);
    }

    dijkstra (P1, best1);           // find shortest distances from P1 to other nodes
    dijkstra (P2, best2);           // find shortest distances from P2 to other nodes

    int ans = best1[P0]+best1[P2];  // path: PB->...->PA1->...->PA2
    if (best2[P0]+best2[P1] < ans) 
        ans = best2[P0]+best2[P1];  // path: PB->...->PA2->...->PA1
    outp << ans << endl;
    return 0;
}

这个代码 if (next.length != best[next.dest]) continue; 用来做什么?是为了避免执行循环时得到与我们已经拥有的答案相同的情况吗?
谢谢!

我不熟悉这个算法,但是你是指e1.length < e2.length吗? - Marlon
2
不,我并不是真的这么想。这是一个最短路径算法,越短越好。 - joshim5
2个回答

2
那一行代码是为了解决C++的优先队列(priority_queue)没有decrease_key函数的问题。也就是说,当你执行pq.push(e)时,如果堆中已经有一个与该边相同目的地的边,则你希望减少已经在堆中的边的键值。这在C++的priority_queue中不容易实现,因此一种简单的处理方法是允许多个对应于相同目的地的边存在于堆中,并忽略从堆中弹出的除第一个(对于每个目的地)以外的所有边。
请注意,这会将复杂度从O(ElogV)更改为O(ElogE)。

1

我猜你正在考虑一个情况,即你的priority_queue包含两次相同的边,但每个边都有不同的"长度"。

这可能发生在你推入边X并且它的长度为Y之后,然后再次推入边X,但这次它的长度小于Y。因此,如果那条边的长度不是迄今为止找到的最低长度,你就在那个循环的迭代中忽略它。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接