最短路径之Bellman-Ford算法

锦妖和她的小伙伴们 2018-04-15

第一行为源点个数,边的个数m

接下来m行为a->b和权值

5 5
2 3 2
1 2 -3
1 5 5
4 5 2
3 4 3

Bellman-Ford算法(1):

1 #include<iostream>
 2 #include<cstdio>
 3 #include<algorithm>
 4 #define inf 1000000000
 5 using namespace std;
 6 int main()
 7 {
 8     int dis[100], u[100], v[100], w[100];
 9     int n, m;
10     cin >> n >> m;
11     for (int i = 1; i <= m; i++)
12         cin >> u[i] >> v[i] >> w[i];
13     for (int i = 1; i <= n; i++)
14         dis[i] = inf;
15     dis[1] = 0;
16     for (int k = 1; k < n; k++)
17         for (int i = 1; i <= m; i++)
18             dis[v[i]] = min(dis[v[i]], dis[u[i]] + w[i]);
19     for (int i = 1; i <= n; i++)
20         cout << dis[i] << " ";
21     return 0;
22 }