# C--最短路（Bellman-Ford算法)

## C–最短路

Time Limit: 7000MS Memory Limit: 65536KB
Submit Statistic
Problem Description

Input

Output

Example Input

3 1
1 2 3
1 2
Example Output

3
Hint

Author

zmx

1.单源最短路径
2.有向图和无向图
3.边权可正可负
4.差分约束系统

``````#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXN 10000000
#define INF 0x3f3f3f3f
int v[MAXN], u[MAXN], dist[MAXN], w[MAXN];
int main()
{
int n, m, a, b, c, s, e, t;
while(~scanf("%d %d", &n, &m))
{
t = 1;//记录边数，由于是无向图，t=m*2
for(int i=1;i<=m;i++)
{
scanf("%d %d %d", &a, &b, &c);
u[t] = a, v[t] = b, w[t] = c;
t++;
u[t] = b, v[t] = a, w[t] = c;
t++;
}
m = m*2;
scanf("%d %d", &s, &e);
for(int i=1;i<=n;i++)
{
dist[i] = INF;//初始化dist数组
}
dist[s] = 0;
int f;//标记
for(int i=0;i<n-1;i++)
{
f = 0;
for(int j=1;j<=m;j++)
{
if(dist[v[j]]>dist[u[j]]+w[j])
{
dist[v[j]]=dist[u[j]]+w[j];
f = 1;
}
}
if(f==0)//当不能再松弛时，跳出
break;
}
printf("%d\n", dist[e]);
}
return 0;
}
``````

SPFA:

……………………………………

``````#include <stdio.h>
#include <string.h>
#define INF 0x3f3f3f3f
int tp, op;
int dist[500023], u[4000023], v[4000023], w[4000023];
int main()
{
int n, m, a, b, c, s, e, k, t;
while(~scanf("%d %d", &n, &m))
{
tp = op = 0;
memset(book, -1, sizeof(book));

t = 1;
for(int i=1;i<=m;i++)
{
scanf("%d %d %d", &a, &b, &c);
u[t] = a, v[t] = b, w[t] = c;
t++;
u[t] = b, v[t] = a, w[t] = c;
t++;
}

scanf("%d %d", &s, &e);
for(int i=1;i<=n;i++)
{
dist[i] = INF;
}
dist[s] = 0;

m = m*2;
book[s] = 1;
while(op<tp)
{
op++;
while(k<=m)
{
if(dist[v[k]]>dist[u[k]]+w[k])
{
dist[v[k]] = dist[u[k]] + w[k];
if(book[k]==0)
{
book[v[k]] = 1;
}
}
k++;
}
}
printf("%d\n", dist[e]);
}
return 0;
}

/***************************************************
User name:
Result: Accepted
Take time: 916ms
Take Memory: 1840KB
Submit time:
****************************************************/``````
``````#include <stdio.h>
#include <string.h>
#define INF 0x3f3f3f3f
int tp, op;
int dist[500023], u[4000023], v[4000023], w[4000023];
int main()
{
int n, m, a, b, c, s, e, k, t;
while(~scanf("%d %d", &n, &m))
{
tp = op = 0;
memset(book, -1, sizeof(book));

t = 1;
for(int i=1;i<=m;i++)
{
scanf("%d %d %d", &a, &b, &c);
u[t] = a, v[t] = b, w[t] = c;
t++;
u[t] = b, v[t] = a, w[t] = c;
t++;
}

scanf("%d %d", &s, &e);
for(int i=1;i<=n;i++)
{
dist[i] = INF;
}
dist[s] = 0;

m = m*2;
book[s] = 1;
while(op<tp)
{
op++;
while(k<=m)
{
if(dist[v[k]]>dist[u[k]]+w[k])
{
dist[v[k]] = dist[u[k]] + w[k];
if(book[k]==0)
{
book[v[k]] = 1;
}
}
k++;
}
}
printf("%d\n", dist[e]);
}
return 0;
}

/***************************************************
User name:
Result: Runtime Error
Take time: 0ms
Take Memory: 0KB
Submit time:
****************************************************/``````
原文作者：Bellman - ford算法
原文地址: https://blog.csdn.net/FEATHER2016/article/details/76528034
本文转自网络文章，转载此文章仅为分享知识，如有侵权，请联系博主进行删除。