zoukankan      html  css  js  c++  java
  • TSP 旅行商问题(状态压缩dp)

    题意:有n个城市,有p条单向路径,连通n个城市,旅行商从0城市开始旅行,那么旅行完所有城市再次回到城市0至少需要旅行多长的路程。

    思路:n较小的情况下可以使用状态压缩dp,设集合S代表还未经过的城市的集合,那么dp[S][v]:当前旅行商还有集合S中的城市没有旅行,并且在城市v时走过的所有路径长度

    参考代码:

    #define _CRT_SECURE_NO_DEPRECATE
    #include<iostream>
    #include<algorithm>
    #include<string>
    #include<set>
    #include<map>
    #include<vector>
    #include<queue>
    #include<functional>
    using namespace std;
    const int N_MAX=16;
    int n,p;//p为单向路径的数量
    int d[N_MAX][N_MAX];
    int dp[1<<N_MAX][N_MAX];//dp[S][v]:集合S:还未去过的城市集合,v当前所在的城市,dp[0][0]表示所有城市都去过,且当前在0城市,所走过的路程
    int main() {
        scanf("%d%d",&n,&p);
        for (int i = 0; i < n; i++)
            fill(d[i], d[i] + n, INT_MAX / 2);
        for (int i = 0; i < p; i++) {
            int a, b, c;
            scanf("%d%d%d", &a, &b, &c);
            d[a][b] = c;
        }
            for (int S = 0; S < 1 << n;S++) {
                fill(dp[S], dp[S] + n,INT_MAX/2);
            }
            dp[(1 << n) - 1][0] = 0;
            for (int S = (1 << n) - 1; S >= 0; S--) {
                for (int v = 0; v < n;v++) {//若当前在v城市
                    for (int u = 0; u < n; u++) {
                        if (S >> u & 1) {//若u还没去过
                            dp[S&~(1 << u)][u] = min(dp[S&~(1 << u)][u],dp[S][v]+d[v][u]);
                        }
                    }
                }
            }
            printf("%d
    ",dp[0][0]);
       
    return 0;
    }
        
  • 相关阅读:
    正则表达式
    正则表达式的lastIndex属性
    vuejs 在移动端调起键盘并触发‘前往’按钮
    适配手机端之 rem
    prototype和_proto_
    ES6 class的继承-学习笔记
    js-null 、undefined
    ES6 class的基本语法-学习笔记
    chrome插件 - Manifest文件中的 background
    别踩白块
  • 原文地址:https://www.cnblogs.com/ZefengYao/p/6683079.html
Copyright © 2011-2022 走看看