所以我试图使用修改后的贝尔曼福特算法来找到从起始顶点到结束顶点的最短路径,但我不能超过一定的距离。所以给定一个带边的图:
0 1 100 30
0 4 125 50
1 2 50 250
1 2 150 50
4 2 100 40
2 3 90 60
4 3 125 150
其中每条线代表一条边,第一个值是起始顶点,第二个值是结束顶点,第三个是成本,第四个是距离。使用我现在拥有的代码,当我尝试找到从 0 到 3 的最便宜路径而不超过 140 时,它会产生 0(未找到路径时的默认值)而不是 340(最便宜路径的成本)。有关如何更改我的代码的任何建议。
只需将代码复制到下面,因为该站点不允许我做任何其他事情。
static void BellmanFord(struct Graph *graph, int source, int ending, int max){
int edges = graph->edgeCount;
int vertices = graph->verticesCount;
int* money = (int*)malloc(sizeof(int) * vertices);
int* distance = (int*)malloc(sizeof(int) * vertices);
for (int I = 0; I < vertices; I++){
distance[I] = INT_MAX;
money[I] = INT_MAX;
}
distance[source] = 0;
money[source] = 0;
for (int I = 1; I <= vertices - 1; ++I){
for int j = 0; j < edges; ++j){
int u = graph->edge[j].Source;
int v = graph->edge[j].Destination;
int Cost = graph->edge[j].cost;
int Duration = graph->edge[j].duration;
if ((money[u] != INT_MAX) && (money[u] + Cost < money[v])){
if (distance[u] + Duration <= max){
money[v] = money[u] + Cost;
distance[v] = distance[u] + Duration;
}
}
}
}
if (money[ending] == INT_MAX) cout << "0" << endl;
else cout << money[ending] << endl;
}
请帮忙!这可能不是那么难,但决赛让我压力山大