生成一个旅行商问题的c++代码
时间: 2024-03-06 21:50:26 浏览: 74
以下是一个简单的旅行商问题的C++代码,它使用贪心算法来近似解决问题:
```c++
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
int n;
cout << "请输入城市数量:";
cin >> n;
vector<vector<int>> distances(n, vector<int>(n));
cout << "请输入" << n << "x" << n << "的距离矩阵:\n";
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cin >> distances[i][j];
}
}
vector<int> path(n);
for (int i = 0; i < n; i++) {
path[i] = i;
}
int total_distance = 0;
for (int i = 0; i < n - 1; i++) {
int min_distance = distances[path[i]][path[i + 1]];
int min_index = i + 1;
for (int j = i + 2; j < n; j++) {
if (distances[path[i]][path[j]] < min_distance) {
min_distance = distances[path[i]][path[j]];
min_index = j;
}
}
total_distance += min_distance;
swap(path[i + 1], path[min_index]);
}
total_distance += distances[path[n - 1]][path[0]];
cout << "最短路径为:";
for (int i = 0; i < n; i++) {
cout << path[i] << " ";
}
cout << "\n";
cout << "路径长度为:" << total_distance << endl;
return 0;
}
```
该代码首先读入城市数量和距离矩阵,然后使用贪心算法求解最短路径,并输出路径和路径长度。
阅读全文