用c++动态规划法解决旅行商问题,要求信息由txt文件读入,文件信息为每个点的坐标,给出具体的代码,每个点的x坐标和y坐标分别存储到两个数组里,txt格式为1 1000.98 500.264
时间: 2024-02-12 18:03:58 浏览: 31
好的,以下是用C++动态规划法解决旅行商问题的代码,其中信息由txt文件读入,文件信息为每个点的坐标,每个点的x坐标和y坐标分别存储到两个数组里。
```
#include <iostream>
#include <fstream>
#include <vector>
#include <cmath>
#include <algorithm>
using namespace std;
const int N = 20; // 最大点数
const int INF = 0x3f3f3f3f; // 无穷大
int n; // 点的数量
int dist[N][N]; // 两点之间的距离
int dp[1 << N][N]; // dp数组,用于记录状态和最小值
vector<int> path[1 << N][N]; // 记录路径
// 读取txt文件,获取点的坐标
void readPoints(string filename, vector<double>& x, vector<double>& y) {
ifstream fin(filename);
double tx, ty;
while (fin >> tx >> ty) {
x.push_back(tx);
y.push_back(ty);
}
}
// 计算两点之间的距离
int getDist(int i, int j, vector<double>& x, vector<double>& y) {
double dx = x[i] - x[j];
double dy = y[i] - y[j];
return (int)round(sqrt(dx * dx + dy * dy));
}
// 初始化距离矩阵
void initDist(vector<double>& x, vector<double>& y) {
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
dist[i][j] = dist[j][i] = getDist(i, j, x, y);
}
}
}
// 动态规划求解旅行商问题
void tsp() {
// 初始化dp数组
for (int i = 0; i < (1 << n); i++) {
fill(dp[i], dp[i] + n, INF);
}
dp[1][0] = 0; // 起点为0,状态为00001
// i表示状态,j表示当前所在的点
for (int i = 1; i < (1 << n); i += 2) {
for (int j = 0; j < n; j++) {
if (!(i & (1 << j))) continue; // 当前状态中不包含j,跳过
// 枚举上一步的状态,即去掉当前点j的状态
for (int k = 0; k < n; k++) {
if (!(i ^ (1 << j) ^ (1 << k))) continue; // 当前状态中只包含j和k,跳过
if (!(i & (1 << k))) continue; // 上一步状态中不包含k,跳过
// 更新dp数组和路径
int cost = dp[i ^ (1 << j)][k] + dist[k][j];
if (cost < dp[i][j]) {
dp[i][j] = cost;
path[i][j] = path[i ^ (1 << j)][k];
path[i][j].push_back(j);
}
}
}
}
}
// 输出结果
void printResult() {
cout << "最短路径长度为:" << dp[(1 << n) - 1][0] << endl;
cout << "路径为:";
vector<int> resPath = path[(1 << n) - 1][0];
for (int i = 0; i < resPath.size(); i++) {
cout << resPath[i] << " ";
}
cout << endl;
}
int main() {
// 读取txt文件,获取点的坐标
vector<double> x, y;
readPoints("points.txt", x, y);
n = x.size();
// 初始化距离矩阵
initDist(x, y);
// 动态规划求解旅行商问题
tsp();
// 输出结果
printResult();
return 0;
}
```
注:txt文件中的每个点的坐标应该按行存储,每行两个数,分别为x坐标和y坐标,中间用空格隔开。