旅行商问题

如果有n个城市,假设每两个城市之间都有通路,且距离已知。现在商人在其中一个城市,想出发经过所有其它城市并回到原地,请求出一条最短路径。

下面对如上问题的一个具体实例进行求解:
n = 4, 商人在A城市
在这里插入图片描述

为了表示方便,A、B、C、D分别用 0、1、2、3代替。
运行结果如下:
(答案 0 2 1 3 0 也对)
在这里插入图片描述
可以使用基于优先队列的分支限界法解决此问题
代码如下:

#include <iostream>
#include <queue>
#include <vector>
#include <algorithm>
#define MAX_V 100
using namespace std;


struct Node{
	int l;  //当前层次
	int d;  //当前距离
	int* x; //当前的排列

	Node(int l, int d, int x[], int n, int i = 0, int j = 0){
		this->l = l;
		this->d = d;
		this->x = new int[n + 1];
		this->n = n;
		for(int a = 0; a < n + 1; a++){
			this->x[a] = x[a];
		}
		//交接i,j位置的值
		int t = this->x[i];
		this->x[i] = this->x[j];
		this->x[j] = t;
	}
	
	~Node(){
		delete[] x;
	}

private:
	int n;
};

struct cmp{
	bool operator()( Node* &a, Node* &b){
		return a->d > b->d;
	}
};

/* 旅行商问题
 * map : 图的邻接矩阵
 * n   : 顶点个数
 * x   : 用于返回最优的顶点排列
 * */
void travel(int map[MAX_V][MAX_V], int n, int x[]){
	//初始化结构
	priority_queue<Node*, vector<Node*>, cmp> q;

	//算法开始
	q.push(new Node(1, 0, x, n));
	while(true){
		Node* node = q.top(); q.pop();
		if(node->l == n + 1){
			for(int i = 1; i < n; i++){
				x[i] = node->x[i];
			}
			return;  //返回之间应该把剩下的节点删除,此略
		}

		//扩展子节点
		for(int i = node->l; i < n + 1; i++){
			if((node->l < n) && (i < n) || node->l == n){
				int dis = node->d + map[node->x[i]][node->x[node->l - 1]];
				Node* no = new Node(node->l + 1, dis, node->x, n, node->l, i);
				q.push(no);
			}
		}

		delete node;
	}
}

int main(){

	int map[MAX_V][MAX_V] = {0};
	int x[] = {0,1,2,3,0};

	map[0][1] = map[1][0] = 30;
	map[0][2] = map[2][0] = 6;
	map[0][3] = map[3][0] = 4;
	map[1][2] = map[2][1] = 5;
	map[1][3] = map[3][1] = 10;
	map[2][3] = map[3][2] = 20;

	travel(map, 4, x);
	for(int i = 0; i < 5; i++){
		cout << x[i] << " ";
	}

	return 0;
}

// 密:构造解的方法
// 1.设计解的构造方法(比较难,一般适用于分治,动态规划)
// 2.树中使用指向父节点的指针(通用)
// 3.复制所有可行解到缓冲区,最后留下的就是最优解,注意广度优先和深度优先方法的不同(通用)
// 4.对于二叉树,可以使用堆的思想,记录节点坐标。(特用)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值