1 介绍
本专题用来介绍使用最短路算法(spfa或dijkstra)与其它算法(dfs、二分、拓扑排序、动态规划等等)结合起来解题。
2 训练
题目1:1135新年好
C++代码如下,
//版本1,使用vector来存储图,会有超时风险
#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>
#include <vector>
using namespace std;
const int N = 50010;
int n, m;
int dist[6][N];
bool st[N];
vector<vector<pair<int, int>>> g; //使用vector可能有超时分险
int source[6];
void spfa(int start, int dist[]) {
memset(dist, 0x3f, N * 4);
memset(st, 0, sizeof st);
dist[start] = 0;
queue<int> q;
q.push(start);
st[start] = true;
while (!q.empty()) {
auto t = q.front();
q.pop();
st[t] = false;
for (auto [b, w] : g[t]) {
if (dist[b] > dist[t] + w) {
dist[b] = dist[t] + w;
if (!st[b]) {
q.push(b);
st[b] = true;
}
}
}
}
return;
}
int dfs(int u, int start, int distance) {
if (u > 5) return distance;
int res = 0x3f3f3f3f;
for (int i = 1; i <= 5; ++i) {
if (!st[i]) {
int b = source[i];
st[i] = true;
res = min(res, dfs(u + 1, i, distance + dist[start][b]));
st[i] = false;
}
}
return res;
}
int main() {
cin >> n >> m;
g.resize(n + 10);
source[0] = 1;
for (int i = 1; i <= 5; ++i) cin >> source[i];
for (int i = 0; i < m; ++i) {
int a, b, c;
cin >> a >> b >> c;
g[a].emplace_back(b, c);
g[b].emplace_back(a, c);
}
for (int i = 0; i < 6; ++i) spfa(source[i], dist[i]);
memset(st, 0, sizeof st);
int res = dfs(1, 0, 0);
cout << res << endl;
return 0;
}
//版本2,使用h,e,ne,w数组来存储图
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <queue>
using namespace std;
typedef pair<int, int> PII;
const int N = 50010, M = 200010, INF = 0x3f3f3f3f