题目描述:
TSP裸题。
前言:
复习复习状态压缩dp,每次做都有新的体会。
题解:
转态设计为 dp[s][i] 当前走过城市集合(包括自己)为s,目前所在城市为 i 的最小TSP路径,状态转移方程就不多说了,具体看代码,由于要求的是回路,所以最后还要加一次循环走回起点。
优化:i 每次加 2,因为因为第一位所表示的地方是起点,无论如何都去过,所以这一位一直是1,没有这个优化,这道题只能得90分。
AC Codes:
#include <iostream>
#include <vector>
#include <queue>
#include <stack>
#include <set>
#include <map>
//#include <unordered_set>
//#include <unordered_map>
#include <deque>
#include <list>
#include <iomanip>
#include <algorithm>
#include <fstream>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#define Min(a , b) ((a) < (b) ? (a) : (b))
//#pragma GCC optimize(2)
using namespace std;
typedef long long ll;
//cout << fixed << setprecision(2);
//cout << setw(2);
const int N = 20, M = 1e9 + 7, INF = 0x3f3f3f3f;
int dp[1 << N][N];
int g[N][N];
int main() {
//freopen("/Users/xumingfei/Desktop/ACM/test.txt", "r", stdin);
ios::sync_with_stdio(false);
cin.tie(0), cout.tie(0);
int n;
cin >> n;
int x, y, z;
memset(dp, 0x3f, sizeof(dp));
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
cin >> g[i][j];
dp[1][0] = 0;
for (int s = 1, t = 1 << n; s < t; s += 2) {
for (int i = 0; i < n; i++) {
if (s & 1 << i) {
for (int j = 0; j < n; j++) {
if (i != j && (s & 1 << j)) {
dp[s][i] = Min(dp[s][i], dp[s ^ (1 << i)][j] + g[j][i]);
}
}
}
}
}
int ans = INF;
for (int i = 1; i < n; i++) ans = Min(ans, dp[(1 << n) - 1][i] + g[i][0]);
cout << ans << '\n';
return 0;
}