在刷最短路问题时,能用dijkstra就用dijkstra,千万别为了省事写SPFA,有些莫名其妙的错误(WA)会让你debug好久好久,很浪费时间且影响心情
#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
const int N = 2e5 + 5;
int n, m;
int pos[6];
int cnt;
int head[N];
struct bal {
int to, nxt, val;
};
bal e[N];
void add(int u, int v, int w) {
e[++cnt].nxt = head[u];
e[cnt].to = v;
e[cnt].val = w;
head[u] = cnt;
}
int d[6][N];
bool st[N];
typedef pair <int, int> PII;
void dijkstra(int start , int dist[])
{
memset(dist , 0x3f , N);
dist[start] = 0;
memset(st , 0 , sizeof st);
priority_queue<PII , vector<PII> , greater<PII>> heap;
heap.push({0 , start});
while(heap.size())
{
auto t = heap.top();
heap.pop();
int ver = t.second , distance = t.first;
if(st[ver]) continue;
for(int i = head[ver]; i ; i = e[i].nxt)
{
int j = e[i].to;
int w = e[i].val;
if(dist[j] > dist[ver] + w)
{
dist[j] = dist[ver] + w;
heap.push({dist[j] , j});
}
}
}
}
int kp[7];
bool flag[7];
int ans = 0x3f3f3f3f;
void dfs(int x, int id) {
if(id == 6) {
int f = 0, res = 0;
for(int i = 1; i <= 5; i++) {
int y = kp[i];
res += d[f][pos[y]];
f = y;
}
ans = min(ans, res);
return;
}
for(int i = 1; i <= 5; i++) {
if(flag[i]) continue;
kp[id] = i;
flag[i] = 1;
dfs(i, id + 1);
flag[i] = 0;
}
return ;
}
int main() {
cin >> n >> m;
pos[0] = 1;
for(int i = 1; i <= 5; i++) cin >> pos[i];
for(int i = 1; i <= m; i++) {
int u, v, w;
cin >> u >> v >> w;
add(u, v, w); add(v, u, w);
}
for(int i = 0; i <= 5; i++) dijkstra(pos[i], d[i]);
kp[0] = 0; flag[0] = 1;
dfs(0, 1);
cout << ans << endl;
return 0;
}