0

I'm working on a small project for solving TSP but am experiencing a problem. The idea is to optimize a local part of a non-optimal path by simply finding the best combination. This is accomplished by a simple recursive permutation generating function.

What I want to do now is check whether the current solution has any potential for improvment (logic: not to call permutation function if weight of solution is more than current best).

The problem that I'm having is that the current implementation does improve the solution but does not make it optimal (I've compared the results to a simple brute-force search). I would appreciate if you'd point out my logic flaws or/ and mistakes. M - is cost matrix. help - current solution, best - best solution (class variables)

   void City::Generate(int** M, int* help, int k, int &auxcost, int* best) {
         int cost2 = 0; // текущая цена
         if (k == range){
             for (int i = 0; i < range - 1; i++)
                 cost2 += M[help[i]][help[i + 1]];   

             if (cost2 < auxcost ){
                 auxcost = cost2;   
                 memcpy(best, help,range *sizeof(int)); 
                 changed = true;
             }
         }
         else{
             for (int j2 = k; j2<range; j2++){
                swap(help[k], help[j2]);

                 for (int i = 0; i < range - 1; i++)
                     tcost += M[help[i]][help[i + 1]];


                 if (tcost <= auxcost)
                     Generate(M, help, k + 1, start, end, auxcost, best);
                     swap(help[k], help[j2]);
             }
         }
     }
Cœur
  • 37,241
  • 25
  • 195
  • 267
Greenmachine
  • 292
  • 1
  • 15

1 Answers1

1

As far as I can see, your mistake is in computing tcost to cut the recursion.
You've fixed a place for every city help[0]..help[k]. However, you compute tcost

for (int i = 0; i < range - 1; i++)
    tcost += M[help[i]][help[i + 1]];

for a full permutation, like you've already fixed all cities! In reality, your recursive function could improve the arrangement of help[k+1]..help[range-1] part of current permutation, thus providing more optimal answer than auxcost.

Instead, you should only evaluate part of the permutation which you are not planning to change. The values of help[0], help[1], ..., help[k] would not change if you continue recursion. Thus, if the value x, computed in such manner:

int x = 0;
for (int i = 0; i < k; i++)  // notice the difference in exit condition
    x += M[help[i]][help[i + 1]];

is greater than auxcost, then this branch of recursion will not find optimal solution for sure.

Mike Koltsov
  • 336
  • 3
  • 6
  • Hello Mike. Yes,that was the problem. I've figured it out and didn't post my answer once the problem was solved. But thank you for your time and will to help. – Greenmachine Jan 16 '16 at 09:36