题目链接:https://cn.vjudge.net/contest/388653#problem/B
最短路基础题,使用bellman-ford
#include <iostream> #include <algorithm> #include <cstdlib> #include <cstring> #include <string> #include <cmath> #include <vector> #include <queue> using namespace std; typedef long long ll; const int INF = 1e9 + 7; const int Max = 10005; int n, m, sum, cnt; struct edge { int from, to, value; }e[Max]; void bellman_ford(int start, int end) { int s = start; int d[205]; for (int i = 0; i < n; i++) d[i] = INF; d[s] = 0; for (int k = 1; k <= n; k++) { for (int i = 0; i < cnt; i++) { int x = e[i].from; int y = e[i].to; if (d[x] > d[y] + e[i].value) { d[x] = d[y] + e[i].value; } } } if (d[end] != INF) sum = d[end]; else sum = -1; } int main() { while (cin >> n >> m) { cnt = 0; sum = 0; for (int i = 1; i <= m; i++) { int u, v, w; cin >> u >> v >> w; e[cnt].from = u; e[cnt].to = v; e[cnt].value = w; cnt++; e[cnt].from = v; e[cnt].to = u; e[cnt].value = w; cnt++; } int a, b; cin >> a >> b; bellman_ford(a, b); cout << sum << endl; } return 0; }
原文:https://www.cnblogs.com/zny0222/p/13531723.html