算法训练营|图论第10天 Bellman_ford:优化算法,判断负权算法,单源有限最短路
题目:Bellman_ford:优化算法
题目链接:
94. 城市间货物运输 I (kamacoder.com)
代码:
#include<bits/stdc++.h>
using namespace std;
struct Edge {
int to;
int val;
Edge(int t, int w) :to(t), val(w) {}
};
int main() {
int n, m;
cin >> n >> m;
int p1, p2, val;
vector<list<Edge>>grid(n + 1);
for (int i = 0; i < m; i++) {
cin >> p1 >> p2 >> val;
grid[p1].push_back(Edge(p2, val));
}
int start = 1;
int end = n;
queue<int>que;
vector<bool>InQueue(n + 1, false);
vector<int>minDist(n + 1, INT_MAX);
minDist[start] = 0;
que.push(start);
while (!que.empty()) {
int cur = que.front();
que.pop();
InQueue[cur] = false;
for (Edge edge : grid[cur]) {
int from = cur;
int to = edge.to;
int val = edge.val;
if (minDist[to] > minDist[from] + val) {
minDist[to] = minDist[from] + val;
if (InQueue[to] == false) {
que.push(to);
InQueue[to] = true;
}
}
}
}
if (minDist[end] == INT_MAX) cout << "unconnected" << endl;
else cout << minDist[end] << endl;
}
题目:判断负权算法
题目链接:
95. 城市间货物运输 II (kamacoder.com)
代码:
#include<bits/stdc++.h>
using namespace std;
struct Edge {
int to;
int val;
Edge(int t, int w) :to(t), val(w) {}
};
int main() {
int n, m;
cin >> n >> m;
int p1, p2, val;
vector<vector<int>>grid;
for (int i = 0; i < m; i++) {
cin >> p1 >> p2 >> val;
grid.push_back({ p1,p2,val });
}
int start = 1;
int end = n;
vector<int>minDist(n + 1, INT_MAX);
minDist[start] = 0;
bool flag = false;
for (int i = 1; i <= n ; i++) {
for (vector<int>vec : grid) {
int from = vec[0];
int to = vec[1];
int val = vec[2];
if (i < n) {
if (minDist[from] != INT_MAX && minDist[from] + val < minDist[to]) {
minDist[to] = minDist[from] + val;
}
}
else {
if (minDist[from] != INT_MAX && minDist[from] + val < minDist[to]) {
flag = true;
}
}
}
}
if (flag) {
cout << "circle" << endl;
}
else if (minDist[end] == INT_MAX) {
cout << "unconnected" << endl;
}
else {
cout << minDist[end] << endl;
}
}
题目:单源有限最短路
题目链接:
96. 城市间货物运输 III (kamacoder.com)
代码:
#include<bits/stdc++.h>
using namespace std;
struct Edge {
int to;
int val;
Edge(int t, int w) :to(t), val(w) {}
};
int main() {
int n, m;
cin >> n >> m;
int p1, p2, val;
vector<vector<int>>grid;
for (int i = 0; i < m; i++) {
cin >> p1 >> p2 >> val;
grid.push_back({ p1,p2,val });
}
int src, dst, k;
cin >> src >> dst >> k;
vector<int> minDist(n + 1, INT_MAX);
minDist[src] = 0;
vector<int> minDist_copy(n + 1); // 用来记录上一次遍历的结果
for (int i = 1; i <= k + 1; i++) {
minDist_copy = minDist;
for (vector<int> &vec : grid) {
int from = vec[0];
int to = vec[1];
int val = vec[2];
if (minDist_copy[from] != INT_MAX && minDist[to] > minDist_copy[from] + val) {
minDist[to] = minDist_copy[from] + val;
}
}
}
if (minDist[dst] == INT_MAX) cout << "unreachable" << endl; // 不能到达终点
else cout << minDist[dst] << endl; // 到达终点最短路径
}