Herowaree

swap

Jul 5th, 2020
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.62 KB | None | 0 0
  1. /* improvementSwap() //{ */
  2.  
  3. std::vector<unsigned> tsp_solver::improvementSwap(std::vector<unsigned> solution){
  4. unsigned first_pos, second_pos;
  5. int delta_f, change_value = 0;
  6. for(unsigned i = 1; i < num_cities_ - 1; i++){
  7. for(unsigned j = i + 1; j < num_cities_; j++){
  8. /* delta_f = old edges cost - new edges cost */
  9. if(i + 1 == j){
  10. delta_f = ( dist_[ solution[i - 1] ][ solution[i] ] + dist_[ solution[i] ][ solution[j] ]
  11. + dist_[ solution[j] ][ solution[j + 1] ])
  12. -
  13. ( dist_[ solution[i - 1] ][ solution[j] ] + dist_[ solution[j] ][ solution[i]]
  14. + dist_[ solution[i] ][ solution[j + 1]]);
  15. }else{
  16. delta_f = ( dist_[ solution[i - 1] ][ solution[i] ] + dist_[ solution[i] ][ solution[i + 1] ]
  17. + dist_[ solution[j - 1] ][ solution[j] ] + dist_[ solution[j] ][ solution[j + 1] ])
  18. -
  19. ( dist_[ solution[i - 1] ][ solution[j] ] + dist_[ solution[j] ][ solution[i + 1] ]
  20. + dist_[ solution[j - 1] ][ solution[i] ] + dist_[ solution[i] ][ solution[j + 1] ]);
  21. }
  22.  
  23. if(delta_f > change_value){
  24. change_value = delta_f;
  25. first_pos = i;
  26. second_pos = j;
  27. }
  28. }
  29. }
  30.  
  31. /* change the solution if generates a cheaper route */
  32. if(change_value > 0){
  33. unsigned tmp = solution[first_pos];
  34. solution[first_pos] = solution[second_pos];
  35. solution[second_pos] = tmp;
  36. }
  37.  
  38. return solution;
  39. }
  40.  
  41. //}
Advertisement
Add Comment
Please, Sign In to add comment