#include<stdio.h>
#include<string.h>
#define MAX 100
typedef struct graph {
int vn;
char vertex[MAX];
int cost[MAX][MAX];
int edge[MAX][MAX];
char route[MAX][MAX];
} GH;
int upde = 1;
int num = 0;
void init(GH *gh);
void bellman_ford(GH *gh);
void update(GH *gh);
void clear(char route[MAX]);
void copy(char sour[MAX],char des[MAX],char appe);
void print(char route[MAX][MAX],int vn);
int main() {
GH grph;
GH *gh = &grph;
char buffer = '\0';
int i = 0,j = 0;
scanf("%d",&grph.vn);
buffer = getchar();
for(i = 0; i < grph.vn; i++) {
scanf("%c",&grph.vertex[i]);
buffer = getchar();
}
for(i = 0; i < grph.vn; i++) {
for(j = 0; j < grph.vn; j++) {
scanf("%d",&grph.edge[i][j]);
}
}
for(i = 0; i < grph.vn; i++) {
for(j = 0; j < grph.vn; j++) {
scanf("%d",&grph.cost[i][j]);
}
}
init(gh);
bellman_ford(gh);
printf("总共进行了 %d 次松弛",num - 1);
return 0;
}
void init(GH *gh) {
(*gh).route[0][0] = (*gh).vertex[0];
(*gh).route[0][1] = '\0';
}
void bellman_ford(GH *gh) {
if(upde == 0) {
print((*gh).route,(*gh).vn);
} else {
update(gh);
bellman_ford(gh);
}
}
void update(GH *gh) {
int i = 0,j = 0;
upde = 0;
num++;
for(i = 0; i < (*gh).vn; i++) {
for(j = 0; j < (*gh).vn; j++) {
if((*gh).edge[i][j] == 1) {
if((*gh).cost[0][j] >= (*gh).cost[0][i] + (*gh).cost[i][j]) {
if((*gh).cost[0][j] > (*gh).cost[0][i] + (*gh).cost[i][j]) upde = 1;
(*gh).cost[0][j] = (*gh).cost[0][i] + (*gh).cost[i][j];
clear((*gh).route[j]);
copy((*gh).route[i],(*gh).route[j],(*gh).vertex[j]);
}
}
}
}
}
void clear(char route[MAX]) {
int i = 0;
for(i = 0; i < MAX; i++) {
route[i] = '\0';
}
}
void copy(char sour[MAX],char des[MAX],char appe) {
int i = 0;
for(i = 0; i < strlen(sour); i++) {
des[i] = sour[i];
}
des[i] = appe;
des[i+1] = '\0';
}
void print(char route[MAX][MAX],int vn) {
int i = 0,j = 0;
for(i = 0; i < vn; i++) {
for(j = 0; j < strlen(route[i]) - 1; j++) {
printf("%c->",route[i][j]);
}
if(i == 0&&j == 0) printf("%c->",route[0][0]);
printf("%c\n",route[i][strlen(route[i]) - 1]);
}
}
贝尔曼福特算法 ---- C语言实现
最新推荐文章于 2024-09-29 14:34:48 发布