diff --git a/ortools/constraint_solver/java/routing.i b/ortools/constraint_solver/java/routing.i index 76d7c9ceaa2..3b8b6254d0a 100644 --- a/ortools/constraint_solver/java/routing.i +++ b/ortools/constraint_solver/java/routing.i @@ -145,6 +145,7 @@ import java.util.function.LongUnaryOperator; %rename (compactAssignment) RoutingModel::CompactAssignment; %rename (computeLowerBound) RoutingModel::ComputeLowerBound; %rename (costVar) RoutingModel::CostVar; +%rename (addExtraCost) RoutingModel::AddExtraCost; %rename (costsAreHomogeneousAcrossVehicles) RoutingModel::CostsAreHomogeneousAcrossVehicles; %rename (debugOutputAssignment) RoutingModel::DebugOutputAssignment; %rename (end) RoutingModel::End; diff --git a/ortools/constraint_solver/routing.cc b/ortools/constraint_solver/routing.cc index 6a71e578a32..2a3eab0232a 100644 --- a/ortools/constraint_solver/routing.cc +++ b/ortools/constraint_solver/routing.cc @@ -2147,6 +2147,9 @@ void RoutingModel::CloseModelWithParameters( for (int i = 0; i < same_vehicle_costs_.size(); ++i) { cost_elements.push_back(CreateSameVehicleCost(i)); } + // Add in any extra cost elements + cost_elements.insert(cost_elements.end(), extra_costs_.begin(), extra_costs_.end()); + cost_ = solver_->MakeSum(cost_elements)->Var(); cost_->set_name("Cost"); diff --git a/ortools/constraint_solver/routing.h b/ortools/constraint_solver/routing.h index bfa8e9c71ab..21857acee48 100644 --- a/ortools/constraint_solver/routing.h +++ b/ortools/constraint_solver/routing.h @@ -1072,6 +1072,15 @@ class RoutingModel { } extra_filters_.push_back(filter); } + // Adds a custom extra cost to the list of cost elements that make up the + // objective value + void AddExtraCost(IntVar* intVar) { + CHECK(intVar != nullptr); + if (closed_) { + LOG(WARNING) << "Model is closed, cost addition will be ignored."; + } + extra_costs_.push_back(intVar); + } /// Model inspection. /// Returns the variable index of the starting node of a vehicle route. @@ -1679,6 +1688,7 @@ class RoutingModel { std::vector filters_; std::vector feasibility_filters_; std::vector extra_filters_; + std::vector extra_costs_; #ifndef SWIG std::vector> finalizer_variable_cost_pairs_; std::vector> finalizer_variable_target_pairs_;