状压换板子—最短哈密顿路径
作者:
春江花月夜ovo
,
2024-03-21 13:17:42
,
所有人可见
,
阅读 16
下标为1写法
#include <bits/stdc++.h>
using namespace std;
typedef long long i64;
typedef pair<int, int> PII;
const int N = 21;
int f[1 << N][N];
int n;
int w[N][N];
int main()
{
ios::sync_with_stdio(false); cin.tie(0);
cin >> n;
for (int i = 1; i <= n; i ++)
for (int j = 1; j <= n; j ++)
cin >> w[i][j];
memset(f, 0x3f, sizeof f);
f[1][1] = 0;
for (int i = 1; i < 1 << n; i ++)
for (int j = 1; j <= n; j ++)
for (int k = 1; k <= n; k ++)
if (!(i & (1 << (k - 1))))
f[i | (1 << (k - 1))][k] = min(f[i | (1 << (k - 1))][k], f[i][j] + w[j][k]);
cout << f[(1 << n) - 1][n] << "\n";
return 0;
}
下标为0写法
#include <bits/stdc++.h>
using namespace std;
typedef long long i64;
typedef pair<int, int> PII;
const int N = 21;
int f[1 << N][N];
int w[N][N];
int n;
int main()
{
ios::sync_with_stdio(false); cin.tie(0);
cin >> n;
for (int i = 0; i < n; i ++)
for (int j = 0; j < n; j ++)
cin >> w[i][j];
memset(f, 0x3f, sizeof f);
f[1][0] = 0;
//下面是关键模板
for (int i = 1; i < 1 << n; i ++)
for (int j = 0; j < n; j ++) //当前走到第j个点
if (f[i][j] < (1 << 30)) //可省略
for (int k = 0; k < n; k ++) //枚举与j相连的状态
if (!(i & (1 << k)))
f[i + (1 << k)][k] = min(f[i + (1 << k)][k], f[i][j] + w[j][k]);
cout << f[(1 << n) - 1][n - 1] << "\n";
return 0;
}