TSP优先队列

#if 0
#include<iostream>
#include<queue>
#include<vector>
using namespace std;

class Travling {
friend void TSP(int**, int);
private:
int n;
int** dis;
int bestc;
};

struct Node {
int v;
int len;
vector<int>path;
bool temp[100] = { false };
Node(){}
Node(int v, int len) :v(v), len(len) {
path.push_back(1);
temp[1] = true;
}
bool operator < (const Node A)const {
return len > A.len;
}
};

void print(vector<int>a) {
cout << "[";
for (auto i = 0; i < a.size() - 1; i++)
cout << a[i] << ", ";
cout << a[a.size() - 1] << "]" << '\n';
}

void TSP(int** a, int n) {
Travling Y;
Y.dis = a;
Y.n = n;
Y.bestc = 9999;
priority_queue<Node>q;
q.push(Node(1, 0));
vector<int>bestpath;
while (!q.empty()) {
Node a = q.top();
q.pop();
print(a.path);
if (a.path.size() == n) {
if (a.len + Y.dis[a.v][1] < Y.bestc) {
Y.bestc = a.len + Y.dis[a.v][1];
bestpath = a.path;
}
}
for (auto i = 1; i <= n; i++) {
if (i == a.v || a.temp[i] == 1)
continue;
a.temp[i] = 1;
Node b = a;
b.v = i;
b.len += Y.dis[a.v][i];
b.path.push_back(i);
if (b.len < Y.bestc)
q.push(b);
a.temp[i] = 0;
}
}
cout << Y.bestc << ": ";
print(bestpath);
}

int main()
{
int n;
cin >> n;
int** a = new int* [n + 1];
for (auto i = 0; i <= n; i++)
a[i] = new int[n + 1];
for (auto i = 1; i <= n; i++)
for (auto j = 1; j <= n; j++)
cin >> a[i][j];
TSP(a, n);
}
/*
4
0 30 6 4
30 0 5 10
6 5 0 20


4 10 20 0
*/
#endif

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值