Files
Data-Structure/Algorithm/DP-DynamicProgramming/Bitmask-DP/货郎担问题TSP.cpp
2025-09-16 23:10:48 +08:00

53 lines
1.2 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include <iostream>
#include <vector>
using namespace std;
const int MAX = INT_MAX >> 1;
int main(){
//n <= 15, S是少于15位的二进制
int n;
cin >> n;
//从0开始
vector<vector<int>> dist(n, vector<int>(n, 0));
vector<vector<int>> dp(n, vector<int>(1 << n, MAX));//dp[i][S];
int N = 1 << n; // 2 ^ n;
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
cin >> dist[i][j];
}
}
int start, end;
cin >> start >> end;
dp[start][1 << start] = 0;
//S到过的城市
//开始操作
for(int mask = 0; mask < N; mask++){
for(int j = 0; j < n; j++){
if(dp[j][mask] == MAX || !(mask & (1 << j))) continue;
for(int v = 0; v < n; v++){
if(mask & (1 << v)) continue;
int new_mask = mask | (1 << v);
//1001 | 0001 = 1001, 1001 ^ 0001 = 1000
dp[v][new_mask] = min(dp[v][new_mask], dp[j][mask] + dist[j][v]);
}
}
}
// 计算最小路径:终点为 end访问所有城市
int full_mask = (1 << n) - 1; // 所有城市都被访问
int cost = dp[end][full_mask];
if (cost == MAX) {
cout << "No valid path" << endl; // 没有可行路径
} else {
cout << cost << endl;
}
return 0;
}
/*
4
0 10 15 20
10 0 35 25
15 35 0 30
20 25 30 0
0 3
*/