贝尔曼-福特算法(Bellman-Ford Algorithm)用于解决单源最短路径问题。下面是一个C++实现的示例代码:
#include
#include
#define INF INT_MAX
// 边的数据结构
struct Edge {
int source, destination, weight;
};
// 图的数据结构
struct Graph {
int V, E;
std::vector edges;
};
// Bellman-Ford算法实现
void BellmanFord(Graph graph, int source) {
int V = graph.V;
int E = graph.E;
std::vector dist(V, INF); // 存储最短距离的数组
dist[source] = 0; // 设置源顶点的最短距离为0
// 对所有边进行V-1次松弛操作
for (int i = 1; i <= V - 1; i++) {
for (int j = 0; j < E; j++) {
int u = graph.edges[j].source;
int v = graph.edges[j].destination;
int weight = graph.edges[j].weight;
if (dist[u] != INF && dist[u] + weight < dist[v]) {
dist[v] = dist[u] + weight;
}
}
}
// 检测是否存在负权回路
for (int i = 0; i < E; i++) {
int u = graph.edges[i].source;
int v = graph.edges[i].destination;
int weight = graph.edges[i].weight;
if (dist[u] != INF && dist[u] + weight < dist[v]) {
std::cout << "图中存在负权回路" << std::endl;
return;
}
}
// 打印最短距离
std::cout << "顶点\t\t最短距离" << std::endl;
for (int i = 0; i < V; i++) {
std::cout << i << "\t\t" << dist[i] << std::endl;
}
}
int main() {
// 创建一个示例图
Graph graph;
graph.V = 5; // 顶点数
graph.E = 8; // 边数
graph.edges = {
{0, 1, -1},
{0, 2, 4},
{1, 2, 3},
{1, 3, 2},
{1, 4, 2},
{3, 2, 5},
{3, 1, 1},
{4, 3, -3}
};
int source = 0; // 源顶点
BellmanFord(graph, source);
return 0;
}
这是一个简单的贝尔曼-福特算法实现,它可以处理包含负权边的图。该实现使用了邻接表的形式来表示图,并在每次迭代中对所有边进行松弛操作。最后,它会检测是否存在负权回路,并打印出最短距离。在main
函数中,我们创建了一个示例图,并指定源顶点。运行程序后,将输出每个顶点到源顶点的最短距离。
下一篇:贝尔曼-福特算法的短前导数组