Search code examples
c++traveling-salesman

3-opt optimization code for TSP


I have this code (tsp problem) that works for the 2-opt optimization and i'd like to change it for a 3-opt optimization. I know i must add a for, but don't really understand the range of the third for. Can you help me?

    double bestDecrement = tsp.infinite;
    // intial and final position are fixed (initial/final node remains 0)
    for ( uint a = 1 ; a < currSol.sequence.size() - 2 ; a++ ) 
    {
        int h = currSol.sequence[a-1];
        int i = currSol.sequence[a];
        for ( uint b = a + 1 ; b < currSol.sequence.size() - 1 ; b++ ) 
        {
            int j = currSol.sequence[b];
            int l = currSol.sequence[b+1];
            double neighDecrement = - tsp.cost[h][i] - tsp.cost[j][l] + tsp.cost[h][j] + tsp.cost[i][l] ;
            if ( neighDecrement < bestDecrement ) 
            {
                bestDecrement = neighDecrement;
                move.from = a;
                move.to = b;
            }
        }
    }

Solution

  • Basically you are looking for 3 edges to remove and then reinsert. So for example:

    for ( uint a = 1 ; a < currSol.sequence.size() - 3 ; a++ ) 
        ...
        for ( uint b = a + 1 ; b < currSol.sequence.size() - 2 ; b++ ) 
            ...
            for ( unit c = b + 1 ; c < currSol.sequence.size() - 1 ; c++)
                ...
    

    The trickier part is determining the new costs, since there are a few feasible reinsertions (as opposed to just one in 2-opt).