旅行商问题
一名销售人员在一家城市中,他必须访问其他所有列出的城市,同时也提供了从一个城市到另一个城市旅行的成本。找到一条成本最低的路线,以访问所有城市一次并返回他的出发城市。
对于这种情况,图表必须是完整的,因此销售人员可以直接从任何城市到任何城市。
在这里,我们必须找到加权最小的哈密顿环。
输入和输出
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
广告