#include <cmath>
#include <vector>
struct DataModel {
const std::vector<std::vector<int>> locations{
{4, 4}, {2, 0}, {8, 0}, {0, 1}, {1, 1}, {5, 2}, {7, 2}, {3, 3}, {6, 3},
{5, 5}, {8, 5}, {1, 6}, {2, 6}, {3, 7}, {6, 7}, {0, 8}, {7, 8},
};
const int num_vehicles = 1;
DataModel() {
for (auto& it : const_cast<std::vector<std::vector<int>>&>(locations)) {
it[0] *= 114;
it[1] *= 80;
}
}
};
std::vector<std::vector<int64>> GenerateManhattanDistanceMatrix(
const std::vector<std::vector<int>>& locations) {
std::vector<std::vector<int64>> distances = std::vector<std::vector<int64>>(
locations.size(), std::vector<int64>(locations.size(),
int64{0}));
for (int fromNode = 0; fromNode < locations.size(); fromNode++) {
for (int toNode = 0; toNode < locations.size(); toNode++) {
if (fromNode != toNode)
distances[fromNode][toNode] =
int64{std::abs(locations[toNode][0] - locations[fromNode][0]) +
std::abs(locations[toNode][1] - locations[fromNode][1])};
}
}
return distances;
}
void PrintSolution(const RoutingIndexManager& manager,
const RoutingModel& routing, const Assignment& solution) {
LOG(
INFO) <<
"Objective: " << solution.ObjectiveValue();
LOG(
INFO) <<
"Route for Vehicle 0:";
std::stringstream route;
while (routing.IsEnd(
index) ==
false) {
route << manager.IndexToNode(
index).value() <<
" -> ";
distance += routing.GetArcCostForVehicle(previous_index,
index,
int64{0});
}
LOG(
INFO) << route.str() << manager.IndexToNode(
index).value();
LOG(
INFO) <<
"Distance of the route: " << distance <<
"m";
LOG(
INFO) <<
"Problem solved in " << routing.solver()->wall_time() <<
"ms";
}
void Tsp() {
DataModel data;
RoutingIndexManager manager(data.locations.size(), data.num_vehicles,
data.depot);
RoutingModel routing(manager);
const auto distance_matrix = GenerateManhattanDistanceMatrix(data.locations);
const int transit_callback_index = routing.RegisterTransitCallback(
auto from_node = manager.IndexToNode(from_index).
value();
auto to_node = manager.IndexToNode(to_index).
value();
return distance_matrix[from_node][to_node];
});
routing.SetArcCostEvaluatorOfAllVehicles(transit_callback_index);
searchParameters.set_first_solution_strategy(
FirstSolutionStrategy::PATH_CHEAPEST_ARC);
const Assignment* solution = routing.SolveWithParameters(searchParameters);
PrintSolution(manager, routing, *solution);
}
}
int main(
int argc,
char** argv) {
operations_research::Tsp();
return EXIT_SUCCESS;
}