【题目链接】
【算法】
状压DP
f[i][S]表示走的最后一步在i,状态为S
于是我们可以用最短路径 + 状压DP解决此题,由于不存在负边,所以可以用dijkstra+堆优化
【代码】
#include<bits/stdc++.h>
using namespace std;
#define MAXN 16 struct info {
int home,s,dis;
friend bool operator < (info a,info b) {
return a.dis > b.dis;
}
}; int T,N,M,i,j,k,mask,u,v,w;
int dist[MAXN+][MAXN+],f[MAXN+][(<<MAXN)+],vis[MAXN+][(<<MAXN)+];
priority_queue<info> q;
info x; template <typename T> inline void read(T &x) {
int f = ; x = ;
char c = getchar();
for (; !isdigit(c); c = getchar()) { if (c == '-') f = -f; }
for (; isdigit(c); c = getchar()) x = x * + c - '';
x *= f;
}
template <typename T> inline void write(T x) {
if (x < ) { putchar('-'); x = -x; }
if (x > ) write(x/);
putchar(x%+'');
}
template <typename T> inline void writeln(T x) {
write(x);
puts("");
} int main() { read(T); while (T--) {
memset(vis,,sizeof(vis));
read(N); read(M);
for (i = ; i <= N; i++) {
for (j = ; j <= N; j++) {
dist[i][j] = 2e9;
}
}
for (i = ; i <= M; i++) {
read(u); read(v); read(w);
dist[u][v] = min(dist[u][v],w);
dist[v][u] = min(dist[v][u],w);
}
mask = ( << N) - ;
for (i = ; i <= N; i++) {
for (j = ; j <= mask; j++) {
f[i][j] = 2e9;
}
}
f[][] = ;
q.push((info){,,});
while (!q.empty()) {
x = q.top(); q.pop();
if (vis[x.home][x.s]) continue;
vis[x.home][x.s] = ;
for (i = ; i <= N; i++) {
if (x.dis + dist[x.home][i] < f[i][x.s|(<<(i-))]) {
f[i][x.s|(<<(i-))] = x.dis + dist[x.home][i];
q.push((info){i,x.s|(<<(i-)),f[i][x.s|(<<(i-))]});
}
}
}
if (N == ) writeln();
else writeln(f[][(<<N)-]);
} return ; }