【发布时间】:2021-01-19 19:25:01
【问题描述】:
请注意:我不确定这是否适合这里,如果不适合,请转到正确的论坛。
所以我有一个程序试图解决旅行商问题,简称 TSP。
我的代码似乎运行良好,直到我尝试使用 33810 个城市,其中程序在尝试访问位置成本 [69378120] 后崩溃,它只是停止响应并很快结束。
我正在尝试以下代码:
#include <iostream>
#include <stdlib.h>
#include <malloc.h>
#include <fstream>
#include <math.h>
#include <vector>
#include <limits>
using namespace std;
typedef long long int itype;
int main(int argc, char *argv[]) {
itype n;
ifstream fenter;
fenter.open(argv[1]);
ofstream fexit;
fexit.open(argv[2]);
fenter>> n;
double *x;
double *y;
x = (double*) malloc(sizeof(double)*n);
y = (double*) malloc(sizeof(double)*n);
cout<<"N : "<<n<<endl;
for (int p = 0; p < n; p++) {
fenter>> x[p] >> y[p];
}
fenter.close();
int *costs;
costs = (int*) malloc(sizeof(int)*(n*n));
for (int u = 0; u < n; u++) {
for (int v = u+1; v < n; v++) {
itype cost = floor(sqrt(pow(x[u] - x[v], 2) + pow(y[u] - y[v], 2)));
cout<<"U: "<<u<<" V: "<<v<<" COST: "<<cost<<endl;
costs[u*n + v] = cost;
cout<<"POS (u*n + v): "<<(u*n + v)<<endl;
cout<<"POS (v*n + u): "<<(v*n + u)<<endl;
costs[v*n + u] = cost;
}
}
return 0;
}
根据一些验证,成本数组应该使用 9.14493GB,但 Windows 仅给出 0.277497GB。然后在尝试读取成本 [69378120] 后,它会关闭。 目前,我不担心效率,也不担心 TSP 的解决方案,只需要解决这个问题。有什么线索吗?
---更新--- 根据建议,我尝试更改一些内容。结果是下面的代码
int main(int argc, char *argv[]) {
int n;
ifstream entrada;
entrada.open(argv[1]);
ofstream saida;
saida.open(argv[2]);
entrada >> n;
vector<double> x(n);
vector<double> y(n);
for (int p = 0; p < n; p++) {
entrada >> x[p] >> y[p];
}
entrada.close();
vector<itype> costs(n*n);
if(costs == NULL){ cout << "Sem memória!" << endl; return -1;}
for (int u = 0; u < n; u++) {
for (int v = u+1; v < n; v++) {
itype cost = floor(sqrt(pow(x[u] - x[v], 2) + pow(y[u] - y[v], 2)));
costs[u*n + v] = cost;
costs[v*n + u] = cost;
}
}
return 0;
}
问题依旧
【问题讨论】:
-
评论不用于扩展讨论;这个对话是moved to chat。