根据算法导论里面的算法实现的。如下:
#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