旅行商问题

旅行推销员问题(TSP):给定一组城市和每对城市之间的距离,问题是找到访问每个城市一次并返回起点的最短路线。
请注意哈密顿循环和 TSP 之间的区别。哈密顿循环问题是找出是否存在一个巡回演出,每个城市只访问一次。这里我们知道哈密顿环是存在的(因为图是完整的),事实上,很多这样的巡回都存在,问题是找到一个最小权重的哈密顿循环。
例如,考虑右侧图中显示的图形。图中的 TSP 游览是 1-2-4-3-1。旅游费用为10 + 25 + 30 + 15,即80。
这个问题是一个著名的NP-hard问题。这个问题没有多项式时间已知的解决方案。

Examples: 

Output of Given Graph:
minimum weight Hamiltonian Cycle :
10 + 25 + 30 + 15 := 80

在这篇文章中,讨论了一个简单的解决方案的实现。

将城市 1 视为起点和终点。由于路线是循环的,我们可以将任何点视为起点。
全部生成 (n-1)!城市的排列。
计算每个排列的成本并跟踪最小成本排列。
以最低成本返回排列。

// CPP program to implement traveling salesman
// problem using naive approach.
#include <bits/stdc++.h>
using namespace std;
#define V 4

// implementation of traveling Salesman Problem
int travllingSalesmanProblem(int graph[][V], int s)
{
    // store all vertex apart from source vertex
    vector<int> vertex;
    for (int i = 0; i < V; i++)
        if (i != s)
            vertex.push_back(i);

    // store minimum weight Hamiltonian Cycle.
    int min_path = INT_MAX;
    do {

        // store current Path weight(cost)
        int current_pathweight = 0;

        // compute current path weight
        int k = s;
        for (int i = 0; i < vertex.size(); i++) {
            current_pathweight += graph[k][vertex[i]];
            k = vertex[i];
        }
        current_pathweight += graph[k][s];

        // update minimum
        min_path = min(min_path, current_pathweight);

    } while (
        next_permutation(vertex.begin(), vertex.end()));

    return min_path;
}

// Driver Code
int main()
{
    // matrix representation of graph
    int graph[][V] = { { 0, 10, 15, 20 },
                    { 10, 0, 35, 25 },
                    { 15, 35, 0, 30 },
                    { 20, 25, 30, 0 } };
    int s = 0;
    cout << travllingSalesmanProblem(graph, s) << endl;
    return 0;
}
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值