用c语言实现Bellman-Ford算法
时间: 2024-02-12 08:07:04 浏览: 84
以下是用C语言实现Bellman-Ford算法的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#define MAX_VERTICES 1000
#define MAX_EDGES 1000
typedef struct {
int source;
int destination;
int weight;
} Edge;
int vertices_count, edges_count;
Edge edges[MAX_EDGES];
int distances[MAX_VERTICES];
void BellmanFord(int source) {
// 初始化距离数组
for (int i = 0; i < vertices_count; ++i) {
distances[i] = INT_MAX;
}
distances[source] = 0;
// 执行松弛操作
for (int i = 0; i < vertices_count - 1; ++i) {
for (int j = 0; j < edges_count; ++j) {
int u = edges[j].source;
int v = edges[j].destination;
int w = edges[j].weight;
if (distances[u] != INT_MAX && distances[u] + w < distances[v]) {
distances[v] = distances[u] + w;
}
}
}
// 检查是否存在负权回路
for (int i = 0; i < edges_count; ++i) {
int u = edges[i].source;
int v = edges[i].destination;
int w = edges[i].weight;
if (distances[u] != INT_MAX && distances[u] + w < distances[v]) {
printf("Detected negative cycle!\n");
return;
}
}
// 输出结果
printf("Vertex Distance from Source\n");
for (int i = 0; i < vertices_count; ++i) {
printf("%d\t\t%d\n", i, distances[i]);
}
}
int main() {
// 读取输入
scanf("%d %d", &vertices_count, &edges_count);
for (int i = 0; i < edges_count; ++i) {
scanf("%d %d %d", &edges[i].source, &edges[i].destination, &edges[i].weight);
}
// 执行算法
BellmanFord(0);
return 0;
}
```
其中,`BellmanFord`函数表示Bellman-Ford算法的实现,`distances`数组存储每个顶点到源顶点的最短距离,`edges`数组存储所有边的信息。该算法首先初始化距离数组,然后执行`vertices_count - 1`次松弛操作,最后检查是否存在负权回路。如果不存在负权回路,则输出每个顶点到源顶点的最短距离。如果存在负权回路,则输出提示信息。
阅读全文