为何Dijkstra算法不能算出具有负边值的图的最短路径?
因为,如果一个顶点u先被声明为是已知的,那就有可能从另外某个未知顶点v有一条回到u的负的路径,这样的情况下,原先从起始顶点s到u的路径就没有从s到v再回到u好。
下面构造一个明晰的例子。
如上图所示,如果按照Dijkstra算法,先确定A—>E :20,然后是A—>D:100,...,在做到A—>B:210之后,检测B的邻接点发现,A—>B + B—>D(210-150) 比A—>D小(100)。
解决方案:
1.将一个常数a加到每一条边上
这样做是为了出去负值边,再计算新图的最短路径,然后把结果应用到原来的图上。但是,一般这种方案是不可能实现的,因为那些具有许多条边的路径变得比那些具有很少边的路径权重更重了。
2.把赋权的和无权的算法结合起来
具体实现过程:
(1)将起始顶点S放到队列中
(2)在每一阶段取队头元素v,找出v的所有邻接顶点w
(3)若dw > dv + Cv,w,则更新dw的值,并且在w不在队列中的时候再次把它放入队列中
(4)重复这个过程直到队列为空
下面是具体代码实现:
#include <iostream>
#include <queue>
#include <string>
using namespace std;
const int MaxSize = 20;
const int Initify = 99999;
struct ArcNode{
int adjvex;
int weight;
ArcNode* next;
};
struct VertexNode{
char verdex;
ArcNode* firstedge;
};
struct Table{
bool known;
int dist;
string path;
};
class NegativeGraph{
private:
VertexNode adjlist[MaxSize];
int vertexNum, arcNum;
char vertex[MaxSize];
Table T[MaxSize];
public:
NegativeGraph(){
char input;
vertexNum = arcNum = 0;
cout << "please input the nodes:" << endl;
while (cin >> input){
vertex[vertexNum] = input;
adjlist[vertexNum].verdex = input;
adjlist[vertexNum].firstedge = NULL;
vertexNum++;
}
cin.clear();
cout << "please input the edges:" << endl;
char a, b;
int weight;
while (cin >> a >> b >> weight){
ArcNode* s = new ArcNode;
s->weight = weight;
s->adjvex = b - 'A';
s->next = adjlist[a - 'A'].firstedge;
adjlist[a - 'A'].firstedge = s;
arcNum++;
}
cin.clear();
}
void InitializeTable(char start){
int i, j;
for (i = 0; i < vertexNum; i++){
T[i].known = false;
T[i].dist = Initify;
string s1(1, start);
string s2(1, vertex[i]);
T[i].path = s1 +s2;
}
T[start - 'A'].dist = 0;
T[start - 'A'].path = string(1,start);
}
void negativeweighted(char start){
InitializeTable(start);
queue<char> q;
char v, w;
q.push(start);
while (!q.empty()){
v = q.front();
q.pop();
for (ArcNode* s = adjlist[v - 'A'].firstedge; s != NULL; s = s->next){
if (T[s->adjvex].dist > T[v - 'A'].dist + s->weight){
T[s->adjvex].dist = T[v - 'A'].dist + s->weight;
T[s->adjvex].path = T[v - 'A'].path + vertex[s->adjvex];
if (!find(q, vertex[s->adjvex])){//若w不在队列中
q.push(vertex[s->adjvex]);
}
}
}
}
}
bool find(queue<char> q, char v){//检测v是否存在于队列中
queue<char> tmp(q);
while (!tmp.empty()){
if (v == tmp.front()){
return true;
}
tmp.pop();
}
return false;
}
void printTable(){
for (int i = 0; i < vertexNum; i++){
cout << T[i].path << " : " << T[i].dist << endl;
}
}
};
int main(){
NegativeGraph ng;
char v;
cout << "please input the begin node:" << endl;
while (cin >> v){
ng.negativeweighted(v);
ng.printTable();
}
return 0;
}
测试结果:
分析:虽然没有负值圈该算法能够正常工作,但是更新T表每边只执行一次的 情况不再成立。每个顶点最多可以出队|V|次(其余的顶点都与该顶点邻接),因此使用邻接表运行时间是O(|E|*|V|)。通过在任一顶点已经出队|V|+1次后停止算法运行,我们能确保循环终止。