Dynamic Programming Solution for TSP in C++

时间:2017-11-13 06:40:21

标签: c++ algorithm dynamic-programming

I have been trying to implement Dynamic Programming solution for TSP (Travelling Salesperson Problem) in C++. My code compiles but when I try to run the object file the program stops working and I am forced to close it.

Here is the code:

int tsp(std::vector<std::vector<int>> matrix) {

   int n = matrix[0].size();
   std::vector<std::vector<int>> A;  // Vertex, Set-Size
   std::set<int> S;

   for(int i = 0; i < n; ++i) {
       S.insert(i);
   }

   for(int i = 0; i < n; i++) {
       if(S.size() == 2) {
           A[i][2] = matrix[1][i];
       }
       else if(S.size() > 2) {
           std::set<int>::iterator it;
           for(it = S.begin(); it != S.end(); ++it) {
               int s = S.size();
               S.erase(i);
               int sd = S.size();
               int k = *it;
               if((k != i) && (k != 1) && (A[i][s] > (matrix[k][i] + A[k][sd]))) {
                   A[i][s] = matrix[k][i] + A[k][sd];
               }
           }
       }
   }

   return A[1][n];
}

Can someone please point out what mistake I am making.

1 个答案:

答案 0 :(得分:0)

在致电std::vector之前,您需要填写或resize operator[int]。向量基本上是一个保持其大小的数组。因此,任何超出界限的访问都会在运行时导致分段错误(如果你很幸运)或者会破坏你的记忆。

这里有一个矢量矢量,所以你需要迭代两个范围并正确填充(或调整大小)矢量:

std::vector<std::vector<int>> A;  // Vertex, Set-Size
for(int i=size; i>0; --i)
   A.push_back(std::vector<int>);
for(int i=size; i>0; --i)
   for(int j=size; j>0; --j)
     A[i][j] = 0;

更好:

A.resize(size);
for(auto& v : a)        // (since you already have c++11)
  v.resize(size, val);  // fill with val