洛谷 P1171 售货员的难题【状态压缩DP | TSP模板】

题目链接

题目描述:

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;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值