先预处理从$1,a,b,c,d,e$为起点到其他点的单源最短路,暴力枚举所有路径$5!$种,通过查表方式计算路径最小值
#include<bits/stdc++.h>
using namespace std;
const int N = 5e4 + 5, M = 2e5 + 5;
int h[N], ne[M], e[M], w[M], idx;
int tar[6], dist[6][N], vis[N];
void add(int a, int b, int c) {
e[idx] = b;
ne[idx] = h[a];
w[idx] = c;
h[a] = idx++;
}
struct HeapNode {
int id, val;
bool operator < (const HeapNode& t) const {
return val > t.val;
}
};
void dijkstra(int s, int id) {
memset(dist[id], 0x3f, sizeof(dist[id]));
memset(vis, 0, sizeof(vis));
dist[id][s] = 0;
priority_queue<HeapNode> q;
q.push({s, 0});
while(!q.empty()) {
auto node = q.top();
q.pop();
int t = node.id;
if(vis[t]) continue;
vis[t] = true;
for(int i = h[t];i != -1;i = ne[i]) {
int j = e[i];
if(dist[id][j] > dist[id][t] + w[i]) {
dist[id][j] = dist[id][t] + w[i];
q.push({j, dist[id][j]});
}
}
}
}
int main()
{
ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
int n, m;
memset(h, -1, sizeof(h));
cin >> n >> m;
unordered_map<int, int> mp;
tar[0] = 1;
for(int i = 1;i <= 5;i++) cin >> tar[i], mp[tar[i]] = i;
mp[1] = 0;
for(int i = 0;i < m;i++) {
int a, b, c;
cin >> a >> b >> c;
add(a, b, c);
add(b, a, c);
}
for(int i = 0;i <= 5;i++) dijkstra(tar[i], mp[tar[i]]);
sort(tar + 1, tar + 6);
int ans = 0x3f3f3f3f;
do {
int sum = 0;
for(int i = 0;i < 5;i++) {
sum += dist[mp[tar[i]]][tar[i + 1]];
}
ans = min(sum ,ans);
} while(next_permutation(tar + 1, tar + 6));
cout << ans << "\n";
return 0;
}