I don't have my code handy, but here's some suggestions and pseudocode to get you going:
I would solve this by storing a vector as well as your above distance matrix in memory. Something like:
struct Location{
bool visited;
bool mustVisit;
}
Vector<Location> locationVec;
Populate the vector with the locations in your problem, marking whether or not they have to be visited, and always setting visited to false. Then comes the fun part! You need to create permutations of the locationVec. I would do this recursively, something like:
void addLocation(int & curLength, int & maxLength, int & curDistance, Vector<Location> &locationVec, Location* lastVisited)
if(curLenth == maxLength){
//check if currentDistance is less than the previously generated best difference, if so
//replace it
lastVisited->visited=0;
return;
}
//Add the next location
for (int& i : locationVec){
//Check if the location has been visited, and if it must be visited.
//If so: mark as visited, point lastVisited to it, and break
//Also add from lastVisited to the new location to your curDistance
curLength++;
}
addLocation(curLength, maxLength, curDistance, locationVec, lastVisited);
return;
}
That should get you started. Remember to subtract from currentDist when you change visited from visited = 1 to visited = 0, because you're essentially "unvisiting" the city. You may need to keep track of lastlastvisited as well, depending on your exact implementation.
If you need to speed it up (and you probably will, traveling Salesman is very slow), look into Branch and Bound: http://en.wikipedia.org/wiki/Branch_and_bound