hdu2544 bellmanford实现

//hdu2544 


#include <iostream>
#define Infinity 0x3f3f3f3f
using namespace std;

struct Edge_Node
{
	int s,e,c;                          //start end cost 
}	g[10005];

int dist[105];                          //起点到每个点的最短距离

void Bellman_Ford(int n,int m)            //点数n  边数m 
{
	int i,j;
	memset(dist,Infinity,sizeof(dist));
	dist[1]=0;                                     //1是起点
	for(i=2;i<=n;i++)
		for(j=1;j<=m;j++)
		{
			if( dist[ g[j].e ] > dist[ g[j].s ] +g[j].c )
				dist[ g[j].e ] = dist[ g[j].s ] +g[j].c;
			
			if( dist[ g[j].s ] > dist[ g[j].e ] +g[j].c )
				dist[ g[j].s ] = dist[ g[j].e ] +g[j].c;
		}
}

int main()
{
	int n,m,i;
	while(scanf("%d%d",&n,&m),m+n)
	{
		for(i=1;i<=m;i++)
			scanf("%d%d%d",&g[i].s,&g[i].e,&g[i].c);

		Bellman_Ford(n,m);
		
		printf("%d\n",dist[n]);
	}
	return 0;
}

你可能感兴趣的:(c)