读书人

Bellman-Ford最小路径有关问题用C语

发布时间: 2012-04-17 15:06:33 作者: rapoo

Bellman-Ford最小路径问题,用C语言编的程序
#include<stdio.h>
#define MAXSIZE 100
#define INF 32767

typedef struct{
int vertex[MAXSIZE]; //存放顶点
Edge edges[MAXSIZE][MAXSIZE]; //存放边
int n,e; //顶点数,边数
}graph;

int d[MAXSIZE];
graph G;
int s;//源点

void init(graph G,int s)
{
int i;
for(i=0;i<G.n;i++)
d[G.vertex[i]]=INF;
d[G.vertex[s]]=0;
}
void relax(graph G,int u,int v)
{
if(d[G.vertex[v]]>d[G.vertex[u]]+G.edges[u][v])
d[G.vertex[v]]=d[G.vertex[u]]+G.edges[u][v];
}
bool BellmanFordShortPaths(graph G,int s)
{
int i,v;
int u=s;
init(G,s);
for(i=0;i<G.n-1;i++)
{
for(u=0;u<G.n;u++)//这里两个for循环是想对每条边进行松弛,可是我总觉得好像有点不对,但是不会改
for(v=0;v<G.n;v++)
relax(G,u,v);
}
for(u=0;u<G.n;u++)
for(v=0;v<G.n;v++)
if(d[G.vertex[v]]>d[G.vertex[u]]+G.edges[u][v])
return false;
return true;
}

void main()
{
int i,j,t,u,v;
graph G;
printf("请输入顶点数n=");
scanf("%d",&G.n);
printf("请输入边数e=");
scanf("%d",&G.e);
printf("请输入源点:");
scanf("%d",&s);
printf("输入顶点:");
for(i=0;i<G.n;i++)
scanf("%d",&G.vertex[i]);
printf("输入起点u到终点v的边的权值edges[u][v]:\n");
for(t=1;t<G.e;t++)
{
scanf("%d%d",&u,&v);
scanf("%d\n",&G.edges[u][v]);
}
if(BellmanFordShortPaths(G,s))
for(j=0;j<G.n;j++)
printf("从源点s=%d开始的最短路径为%d:",s,d[j]);
}


这个程序我运行不出结果,不知道怎么改,我刚学,想尝试用数据结构却不熟悉,纠结,请哥哥姐姐帮帮我,呜呜~~~
在这段代码中
{
for(u=0;u<G.n;u++)//这里两个for循环是想对每条边进行松弛,可是我总觉得好像有点不对,但是不会改
for(v=0;v<G.n;v++)
relax(G,u,v);
}




[解决办法]
你可以看看这本书 《数据结构(C语言版)》作者: 黄国瑜 里面有完整的源代码 可以参考一下的 祝你好运

[解决办法]
你的代码我改好了:
http://blog.csdn.net/pengtwelve/article/details/6854689
代码有一些明显的错误,而且感觉你没有调试过啊.
[解决办法]
算法导论上有伪代码,松弛么,很简单的。

读书人网 >C语言

热点推荐