• TSP-旅行商问题


    #include <iostream>
    #include <cstring>
    #include <cstdlib>
    #include <climits>
    #include <vector>
    
    #define MAX_N 10
    
    int d[MAX_N][MAX_N];
    
    int dp[1<<MAX_N][MAX_N];
    
    int n;
    
    using namespace std;
    
    int dfs_tsp(int S, int v) {
        if (dp[S][v] >= 0) {
            return dp[S][v];
        }
        if ((1<<n)-1 == S && v == 0) {
            return dp[S][v] = 0;
        }
        
        int res = INT_MAX/2;
        for (int u=0; u<n; u++) {
            if (!((S>>u) & 1)) {
                res = min(res, dfs_tsp(S|(1<<u), u) + d[v][u]);
            }
        }
        return dp[S][v] = res;
    }
    
    
    
    void dfs_path(int S, int v, vector<int>& path) {
        if ((1<<n)-1 == S && v == 0) {
            return;
        }
        
        int res = INT_MAX / 2;
        int idx = -1;
        for (int u=0; u<n; u++) {
            int cdst = dp[S|(1<<u)][u] + d[v][u];
            if (!((S>>u) & 1) && cdst < res) {
                idx = u;
                res = cdst;
            }
        }
        path.push_back(idx);
        dfs_path(S|(1<<idx), idx, path);
    }
    
    int main() {
        n = 5;
        memset(dp, -1, sizeof(dp));
    
        for (int i=0; i<n; i++) {
            for (int j=0; j<n; j++) {
                d[i][j] = INT_MAX/2;
            }
        }
        
        d[0][1] = 3;
        d[0][3] = 4;
        d[4][0] = 7;
        d[4][1] = 6;
        
        d[3][4] = 3;
        d[2][0] = 4;
        d[2][3] = 5;
        d[1][2] = 5;
        
        
        
        int dst = dfs_tsp(0, 0);
        cout<<dst<<endl;
    
        vector<int> path(1,0);
    
        dfs_path(0, 0, path);
        
        for (int e:path) {
            cout<<e<<" ";
        }
    
        system("pause");
        return 0;
    }

    挑战程序设计P193. 其实还可以反向着来,不过实现起来比这个稍烦一些。

  • 相关阅读:
    HDU6808 Go Running(未解决问题
    K
    E
    D
    B
    I
    HDU 2255 奔小康赚大钱 (KM算法模板)
    hdu 1150 Machine Schedule(二分图模板题)
    ACM-ICPC 2018 焦作赛区网络预赛G Give Candies(欧拉降幂)
    ACM-ICPC 2018 焦作赛区网络预赛 L:Poor God Water(杜教BM)
  • 原文地址:https://www.cnblogs.com/lailailai/p/4335921.html
Copyright © 2020-2023  润新知