# 最短路

Time Limit: 5000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 86738    Accepted Submission(s): 37534

Problem Description

Input

Output

Sample Input

2 1
1 2 3
3 3
1 2 5
2 3 5
3 1 2
0 0

Sample Output

3
2

Source

UESTC 6th Programming Contest Online

问题链接:HDU2544最短路

AC的C++程序:

``````#include<iostream>

using namespace std;
const int INF=0x3f3f3f3f;

struct Edge{
int start,end,cost;//从start到end长度为cost的边
}edge[10005];

int dist[105];

bool Bellman_ford(int n,int m)//n结点数，m边数
{
for(int i=1;i<n;i++)
for(int j=0;j<m;j++)
if(dist[edge[j].end]>dist[edge[j].start]+edge[j].cost)
dist[edge[j].end]=dist[edge[j].start]+edge[j].cost;
bool flag=true;
for(int i=0;i<m;i++)
if(dist[edge[i].end]>dist[edge[i].start]+edge[i].cost){
flag=false;
break;
}
return flag;
}

int main()
{
int n,m,a,b,c;
while(scanf("%d%d",&n,&m)!=EOF&&(n||m)){
for(int i=0;i<2*m;i++){
scanf("%d%d%d",&a,&b,&c);
edge[i].start=a,edge[i].end=b,edge[i].cost=c;
i++;
edge[i].start=b,edge[i].end=a,edge[i].cost=c;
}
//初始化
for(int i=1;i<=n;i++)
dist[i]=INF;
dist[1]=0;
bool flag=Bellman_ford(n,2*m);
if(flag)
printf("%d\n",dist[n]);
}
return 0;
}``````

原文作者：Bellman - ford算法
原文地址: https://blog.csdn.net/SongBai1997/article/details/81320883
本文转自网络文章，转载此文章仅为分享知识，如有侵权，请联系博主进行删除。