一个销售人员在一个城市中,他必须访问列出的所有其他城市,还提供了从一个城市到另一个城市的旅行费用。找到费用最低的路线,一次访问所有城市,然后返回他的出发城市。
在这种情况下,该图必须完整,因此销售人员可以直接从任何城市到任何城市。
在这里,我们必须找到最小加权哈密顿循环。
Input: Cost matrix of the matrix. 0 20 42 25 30 20 0 30 34 15 42 30 0 10 10 25 34 10 0 25 30 15 10 25 0 Output: Distance of Travelling Salesman: 80
travellingSalesman (mask, pos)
有一个表dp,并且VISIT_ALL值用来标记所有已访问的节点
输入- 用于遮罩某些城市,位置的遮罩值。
输出减;找到访问所有城市的最短路线。
Begin if mask = VISIT_ALL, then //when all cities are visited return cost[pos, 0] if dp[mask, pos] ≠ -1, then return dp[mask, pos] finalCost := ∞ for all cities i, do tempMask := (shift 1 left side i times) if mask AND tempMask = 0, then tempCpst := cost[pos, i] + travellingSalesman(mask OR tempMask, i) finalCost := minimum of finalCost and tempCost done dp[mask, pos] = finalCost return finalCost End
#include<iostream>
#define CITY 5
#define INF 9999
using namespace std;
int cost[CITY][CITY] = {
{0, 20, 42, 25, 30},
{20, 0, 30, 34, 15},
{42, 30, 0, 10, 10},
{25, 34, 10, 0, 25},
{30, 15, 10, 25, 0}
};
int VISIT_ALL = (1 << CITY) - 1;
int dp[16][4]; //make array of size (2^n, n)
int travellingSalesman(int mask, int pos) {
if(mask == VISIT_ALL) //when all cities are marked as visited
return cost[pos][0]; //from current city to origin
if(dp[mask][pos] != -1) //when it is considered
return dp[mask][pos];
int finalCost = INF;
for(int i = 0; i<CITY; i++) {
if((mask & (1 << i)) == 0) { //if the ith bit of the result is 0, then it is unvisited
int tempCost = cost[pos][i] + travellingSalesman(mask | (1 << i), i); //as ith city is visited
finalCost = min(finalCost, tempCost);
}
}
return dp[mask][pos] = finalCost;
}
int main() {
int row = (1 << CITY), col = CITY;
for(int i = 0; i<row; i++)
for(int j = 0; j<col; j++)
dp[i][j] = -1; //initialize dp array to -1
cout << "Distance of Travelling Salesman: ";
cout <<travellingSalesman(1, 0); //initially mask is 0001, as 0th city already visited
}输出结果
Distance of Travelling Salesman: 80