题解 | #毕业旅行问题#

毕业旅行问题

https://www.nowcoder.com/practice/3d1adf0f16474c90b27a9954b71d125d

import java.util.*;
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int[][] map = new int[n][n];
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                map[i][j] = sc.nextInt();
            }
        }
        int min = minTsp(map, n);
        System.out.println(min);
    }

    // drd notes: 城市不大于20个, 故可以用int的低20位来保存状态!
    public static int minTsp(int[][] map, int n) {
        int stateCount = (int) Math.pow(2, n - 1);
        int[][] dp = new int[n][stateCount];
        map[0][0] = Integer.MAX_VALUE;
        for (int city = 0; city < n; city++) {
            dp[city][0] = map[city][0];
        }
        for (int state = 1; state < stateCount; state++) {
            for (int city = 0; city < n; city++) {
                // 从city出发,经过state状态的城市集合,最终到达0城市,最小花费dp[city][state]
                dp[city][state] = Integer.MAX_VALUE;
                // 假如state包含城市city,不应该存在这种情况,故默认最大值即可
                if (city != 0 && hasVisited(state, city)) {
                    continue;
                }
                // 比如city包含4个城市,就拆为4个小问题,每个小问题包含3个城市
                for (int subCity = 1; subCity < n; subCity++) {
                    if (hasVisited(state, subCity)) {
                        int subState = 1 << (subCity - 1);
                        // 排除cityId后state
                        subState ^= state;
                        dp[city][state] = Math.min(dp[city][state], map[city][subCity] + dp[subCity][subState]);
                    }
                }
            }
        }
        return dp[0][dp[0].length - 1];
    }

    private static boolean hasVisited(int cities, int city) {
        return (cities >> city - 1 & 1) == 1;
    }
}



1.重点是状态state的理解,比如state=10,则state=1010,即中间经过第2、第4 两座城市。这是因为城市小于等于20,并且1个城市默认是终点和起点(我们这里假设城市0是起点和终点),故可以用int的第19位表示 城市1到城市19是否旅行过
2.dp[0][1111...1111]表示从城市0出发,经过了其他(n-1)个城市,再到城市0的最小花费
3.动态规划要从state不断递增

时间复杂度:O(2^(n-1) * n * n) = O(n^2 * 2^n)
空间复杂度:O(2^n)

#毕业旅行##字节笔试#
全部评论

相关推荐

06-02 15:17
门头沟学院 Java
心爱的idea:怎么会呢 应该是打招呼有问题 问就说实习6个月全国可飞随时到岗
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务