状压TSP问题
TSP问题
从一个点出发经过所有的点回到这个点的最短路径
dp[i][j] 表示的是从起点出发到达 i 点, 且状态为 j 是的最小花费
答案取 \(min_{i = 1}^n(dp[i][(1<<n) - 1] + G[i][st])\)
#include<bits/stdc++.h>
using namespace std;
const int N = 21;
int dp[N][(1 << 20) + 20];
int G[N][N];
int n;
int main() {
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
scanf("%d", &G[i][j]);
}
}
memset(dp, 0x3f, sizeof dp);
dp[1][1] = 0;
for (int i = 0; i < (1 << n); i++) {
for (int j = 1; j <= n; j++) {
if (i & (1 << (j - 1)))continue;
for (int k = 1; k <= n; k++) {
if (i & (1 << (k - 1)) == 0)continue;
dp[j][i | (1 << (j - 1))] = min(dp[j][i | (1 << (j - 1))], dp[k][i] + G[k][j]);
}
}
}
int ans = 0x3f3f3f3f;
for (int i = 1; i <= n; i++) {
ans = min(ans, dp[i][(1 << n) - 1] + G[i][1]);
}
printf("%d\n", ans);
}
就可以解决牛客day2 的B题了