# Bellman-Ford算法实现

``````#include <stdio.h>

struct vertex
{
int weight;
int dist;
int parent;
};

#define MAX_SIZE    50
struct vertex data[MAX_SIZE][MAX_SIZE];
int size;
int source;
#define MAX_VALUE    (1 << 31 -1 )
//int short_dist[MAX_SIZE];

void read_data(void)
{
scanf("%d", &source);
int edges;
scanf("%d %d", &size, &edges);

int i, j;
for(i = 0; i < size; i++)
{
for(j = 0; j < size; j++)
{
if(i != j)
{
data[i][j].weight = MAX_VALUE;
}
else
{
data[i][j].weight = 0;
}
}
}

for(i = 0; i < edges; i++)
{
int p, q;
scanf("%d %d", &p, &q);
scanf("%d", &data[p][q].weight);
}
}

void init_single_source(int s)
{
int i;
for(i = 0; i < size; i++)
{
if( i != s)
{
data[s][i].dist = MAX_VALUE;
}
else
{
data[s][i].dist = 0;
}
}
}
int bellman_ford(int s)
{
init_single_source(s);
int k;
for(k = 1; k < size; k++)
{
int i, j;
for(i = 0; i < size; i++)
{
for(j = 0; j < size; j++)
{
if(data[i][j].weight < MAX_VALUE)
{
if(data[s][i].dist < MAX_VALUE && data[s][j].dist > data[s][i].dist + data[i][j].weight)
{
data[s][j].dist = data[s][i].dist + data[i][j].weight;
}
}
}
}
}

int i, j;
for(i = 0; i < size; i++)
{
for(j = 0; j < size; j++)
{
if(data[i][j].weight < MAX_VALUE)
{
if(data[s][j].dist > data[s][i].dist + data[i][j].weight)
{
return 0;
}
}
}
}

return 1;
}

int main(int argc, char **argv)
{
read_data();
int ret = bellman_ford(source);
if(ret == 0)
{
printf("contains a negative cycle\n");
}
else
{
int i;
for(i = 1; i < size; i++)
{
printf("(%d, %d): %d\n", source, i, data[source][i].dist);
}
//        printf("ok\n");
}
return 0;
}
``````

``````0
5 10
0 1 6
1 2 5
2 1 -2
0 4 7
1 4 8
1 3 -4
3 2 7
3 0 2
4 3 9
4 2 -3``````

``````(0, 1): 2
(0, 2): 4
(0, 3): -2
(0, 4): 7
``````
原文作者：Bellman - ford算法
原文地址: https://blog.csdn.net/CaspianSea/article/details/52041730
本文转自网络文章，转载此文章仅为分享知识，如有侵权，请联系博主进行删除。