状压dp解决旅行商问题TSP

毕业旅行问题

小明目前在做一份毕业旅行的规划。打算从北京出发,分别去若干个城市,然后再回到北京,每个城市之间均乘坐高铁,且每个城市只去一次。由于经费有限,希望能够通过合理的路线安排尽可能的省一些路上的花销。给定一组城市和每对城市之间的火车票的价钱,找到每个城市只访问一次并返回起点的最小车费花销。

时间限制:C/C++ 1秒,其他语言2秒
空间限制:C/C++ 32M,其他语言64M

输入描述:

城市个数n(1<n≤20,包括北京)

城市间的车票价钱 n行n列的矩阵 m[n][n]

输出描述:

最小车费花销 s

示例1

输入例子:

4
0 2 6 5
2 0 4 4
6 4 0 2
5 4 2 0

输出例子:

13

例子说明:

共 4 个城市,城市 1 和城市 1 的车费为0,城市 1 和城市 2 之间的车费为 2,城市 1 和城市 3 之间的车费为 6,城市 1 和城市 4 之间的车费为 5,依次类推。假设任意两个城市之间均有单程票可购买,且票价在1000元以内,无需考虑极端情况。

题解

我们最终的目的是为找一个包含所有点的最小环。因此可以任意选一个节点(城市)作为出发节点(城市),不会影响最终的效果。这里我们挑选第一个节点(城市:北京)作为出发点节。

首先,我们考虑暴力结题的思路。从一个点出发,任意其他没走过的城市都可以作为备选,从一开始有N-1个备选直到最后只有一个备选。那么时间复杂度就是 O ( n ! ) O(n!) O(n!),这个时间复杂度是非常高的。在规定的时间内无法完成最高20个城市的旅行商问题。

因此我们考虑使用状态压缩的动态规划来解决这个问题,每个城市是否去过用一个bit表示,那么就需要 2 20 = 1048576 2^{20} = 1048576 220=1048576大小的数组就可以表示所有去过哪些城市的状态。我们还需要另一个状态表示当前处于哪一个节点(城市)。

d i s [ i ] [ j ] dis[i][j] dis[i][j] 表示 i i i 节点(城市)和 j j j 节点(城市)的距离。
d p [ v ] [ S ] dp[v][S] dp[v][S] 表示从 1 1 1 节点出发到过 S S S 这些城市且最后停留在 v v v 这个城市所需要的最短路程。接下来我们结合具体数值解释一下 d p [ v ] [ S ] dp[v][S] dp[v][S] 索引的意思,比如 S = 6 S=6 S=6,j换成二进制就是0000 0000 0000 0000 0000 0110,表示 20 20 20个城市目前从 1 1 1 节点出发到过 2 2 2 节点(城市)和 3 3 3 节点(城市); v = 3 v=3 v=3 表示目前停留在 3 3 3 节点(城市)。

由此我们可知只要求得 d p [ 1 ] [ 2 20 − 1 ] dp[1][2^{20}-1] dp[1][2201] 的值就是最终的答案了。这个值我们可以有由最初的状态不断地推导出来,且最初的状态结果是显而易见的。
d p [ v ] [ S ] = { d i s [ 1 ] [ v ] S ⊕ 2 v − 1 = = 0 min ⁡ ( d p [ u ] [ S ⊕ 2 v − 1 ] + d i s [ u ] [ v ] ) S ∣ 2 u − 1 = = 1 \begin{aligned} dp[v][S]=\left\{ \begin{array}{clc} dis[1][v] & & S \oplus 2^{v-1} == 0\\ \min(dp[u][S \oplus 2^{v-1}]+dis[u][v]) & & S | 2^{u-1} == 1 \end{array} \right. \end{aligned} dp[v][S]={dis[1][v]min(dp[u][S2v1]+dis[u][v])S2v1==0S2u1==1

C++代码


#include <bits/stdc++.h>
using namespace std;

int N;  // 节点总数
int dis[21][21];  // 个节点之间的距离
int dp[21][1<<20];  // 第一个状态是最后一站,第二个状态描述目前旅行的地方

int main() {
    cin>>N;
    for(int i=1;i<=N;i++)
    for(int j=1;j<=N;j++){
        scanf("%d", &dis[i][j]);
    }
    memset(dp, 0x3f, sizeof(dp));
    for(int i=1;i<=N;i++){ // 递推公式的第一个条件
        dp[i][(1<<(i-1))] = dis[1][i];
    }
    for(int i=1;i<(1<<N);i++){
        for(int v=1;v<=N;v++){  // 下一个要去的节点
            if(i&(1<<(v-1))) continue;  // 已经去过v节点了
            for(int u=1;u<=N;u++){  // 当前所在节点
                if(!(i&(1<<(u-1)))) continue; // 还没去去过u
                int nxt = i|(1<<(v-1));  // 下一个状态
                if(dp[v][nxt] > dp[u][i]+dis[u][v]){  // 发现更近的路程
                    dp[v][nxt] = dp[u][i]+dis[u][v];
                }
            }
        }
    }
    cout<<dp[1][(1<<N)-1];  // 最后到达了1节点,并且经历过了所有节点。

    return 0;
}
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
TSP问题是指旅行商问题,即在给定的一些城市之间寻找一条最短的路径,使得每个城市恰好被访问一次,最终回到起点城市。Python可以使用多种算法解决TSP问题,其中比较常用的是遗传算法和模拟退火算法。 遗传算法的基本思想是通过模拟生物进化过程来搜索最优解。具体实现中,可以将每个城市看作一个基因,将所有城市的排列看作一个染色体,然后通过交叉、变异等操作来不断优化染色体,最终得到最优解。 模拟退火算法则是通过模拟物质在高温下的运动来搜索最优解。具体实现中,可以将每个城市看作一个状态,然后通过随机游走的方式来不断优化状态,最终得到最优解。 以下是一个使用遗传算法解决TSP问题的示例代码: ```python import random # 城市坐标 cities = [(60, 200), (180, 200), (80, 180), (140, 180), (20, 160), (100, 160), (200, 160), (140, 140), (40, 120), (100, 120), (180, 100), (60, 80), (120, 80), (180, 60), (20, 40), (100, 40), (200, 40), (20, 20), (60, 20), (160, 20)] # 计算两个城市之间的距离 def distance(city1, city2): return ((city1[0] - city2[0]) ** 2 + (city1[1] - city2[1]) ** 2) ** 0.5 # 计算染色体的适应度 def fitness(chromosome): total_distance = 0 for i in range(len(chromosome) - 1): total_distance += distance(cities[chromosome[i]], cities[chromosome[i+1]]) total_distance += distance(cities[chromosome[-1]], cities[chromosome[0]]) return 1 / total_distance # 初始化种群 def init_population(population_size, chromosome_length): population = [] for i in range(population_size): chromosome = list(range(chromosome_length)) random.shuffle(chromosome) population.append(chromosome) return population # 选择操作 def selection(population, fitness_values): total_fitness = sum(fitness_values) probabilities = [fitness_value / total_fitness for fitness_value in fitness_values] selected_indices = random.choices(range(len(population)), weights=probabilities, k=2) return population[selected_indices[0]], population[selected_indices[1]] # 交叉操作 def crossover(parent1, parent2): child = [-1] * len(parent1) start_index = random.randint(0, len(parent1) - 1) end_index = random.randint(start_index, len(parent1) - 1) for i in range(start_index, end_index + 1): child[i] = parent1[i] j = 0 for i in range(len(parent2)): if parent2[i] not in child: while child[j] != -1: j += 1 child[j] = parent2[i] return child # 变异操作 def mutation(chromosome, mutation_rate): for i in range(len(chromosome)): if random.random() < mutation_rate: j = random.randint(0, len(chromosome) - 1) chromosome[i], chromosome[j] = chromosome[j], chromosome[i] return chromosome # 遗传算法主函数 def genetic_algorithm(population_size, chromosome_length, max_generations): population = init_population(population_size, chromosome_length) for generation in range(max_generations): fitness_values = [fitness(chromosome) for chromosome in population] best_chromosome = population[fitness_values.index(max(fitness_values))] print('Generation {}: Best fitness = {}'.format(generation, max(fitness_values))) new_population = [best_chromosome] while len(new_population) < population_size: parent1, parent2 = selection(population, fitness_values) child = crossover(parent1, parent2) child = mutation(child, 0.01) new_population.append(child) population = new_population return best_chromosome # 测试 best_chromosome = genetic_algorithm(100, len(cities), 1000) print('Best chromosome:', best_chromosome) ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值