旅行商问题
一位销售人员身处某个城市,他需要走访其他所有列出的城市,而且提供了从一个城市到另一个城市的路费。找出总路费最低的路线,该路线要走访所有城市一次,然后返回起始城市。
对于本例,图必须是完整的,这样,销售人员才能从任意城市直接前往任意城市。
这里,我们要找到加权哈密顿环的最小值。
输入和输出
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
广告