题意
给定一个包含 \(N\) 个点和 \(M\) 条无向边的带权图,保证图中没有自环,但可能包含重边。
给出 \(Q\) 次查询,每次查询给出 \(K\) 条边 \(B_1,B_2,\cdots ,B_K\),要求求出从节点 \(1\) 到节点 \(N\) 且这 \(K\) 条边都至少经过一次的最短路(经过边的方向和顺序任意)。
赛时 Dijkstra 状态压缩 [TLE]
赛后
由于 \(K\) 很小,因此我们可以枚举经过 \(K\) 条边的顺序和方向,提前预处理出 \(dist\) 数组即可直接计算出最短距离。
代码
#include <iostream>
#include <algorithm>
#include <cstring>
#define x first
#define y second
using namespace std;
typedef long long LL;
typedef pair<int, int> PII;
typedef pair<int, PII> PIP;
const int N = 405, M = 200005;
LL dist[N][N];
PIP edges[M];
int n, m, q, k;
int b[10], perm[10];
int main(){
scanf("%d%d", &n, &m);
memset(dist, 0x3f, sizeof dist);
for (int i = 1; i <= n; i ++ ) dist[i][i] = 0;
for (int i = 1; i <= m; i ++ ){
int u, v, w;
scanf("%d%d%d", &u, &v, &w);
dist[u][v] = dist[v][u] = min(dist[u][v], 1ll * w);
edges[i] = {w, {u, v}};
}
for (int k = 1; k <= n; k ++ )
for (int i = 1; i <= n; i ++ )
for (int j = 1; j <= n; j ++ )
dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]);
scanf("%d", &q);
while (q -- ){
scanf("%d", &k);
for (int i = 1; i <= k; i ++ ) scanf("%d", &b[i]), perm[i] = i;
LL ans = 0x3f3f3f3f3f3f3f3f;
do {
for (int state = 0; state < (1 << k); state ++ ){
LL res = 0, last = 1;
for (int i = 1; i <= k; i ++ ) {
PIP edge = edges[b[perm[i]]];
int from = edge.y.x, to = edge.y.y;
if ((state >> i - 1) & 1) swap(from, to);
res += dist[last][from] + edge.x;
last = to;
}
res += dist[last][n];
ans = min(ans, res);
}
} while (next_permutation(perm + 1, perm + k + 1));
printf("%lld\n", ans);
}
return 0;
}
标签:typedef,dist,int,Tour,abc369,include,luoguAT
From: https://www.cnblogs.com/XiaoJuRuoUP/p/-/luoguAT_abc369_e