
Google
Google OR-Tools TSP 跨越多天并包含开始/停止时间
TSP(Traveling Salesman Problem,旅行商问题)是一个经典的组合优化问题,目标是找到一条最短路径,使得旅行商能够在多个城市之间旅行一次并返回起点。然而,在实际生活中,旅行商可能需要在不同的天数内完成旅行,并且每个城市的访问时间也可能有限制。为了解决这个问题,Google OR-Tools 提供了一个强大的功能,可以跨越多天并包含开始/停止时间的 TSP 问题。多天旅行的问题定义假设我们有一位旅行商,需要在多个城市之间旅行,每个城市都有一个特定的访问时间窗口。我们的目标是找到一条最短路径,使得旅行商能够在每个城市的时间窗口内到达并离开。为了解决这个问题,我们可以使用 Google OR-Tools 中的 Routing Solver。我们需要定义每个城市的位置、时间窗口和旅行时间。然后,我们可以使用 Routing Solver 的 AddDimensionWithVehicleCapacity() 方法来添加一个维度来表示时间。通过设置每个城市的开始时间和停止时间,我们可以确保旅行商在时间窗口内到达和离开每个城市。案例代码下面是一个简单的案例代码,演示了如何使用 Google OR-Tools 解决跨越多天并包含开始/停止时间的 TSP 问题。Pythonfrom ortools.constrAInt_solver import routing_enums_pb2from ortools.constrAInt_solver import pywrapcpdef tsp_with_time_windows(): # Create the solver. routing = pywrapcp.RoutingModel(1, 0) # Define the locations and time windows. locations = [(0, 0), (1, 2), (3, 4), (5, 6)] time_windows = [(0, 5), (1, 4), (2, 3), (1, 5)] # Define the travel time between locations. travel_times = [ [0, 1, 2, 3], [1, 0, 4, 5], [2, 4, 0, 6], [3, 5, 6, 0] ] # Define the time dimension. time_dimension = routing.AddDimension( transit_callback_index=0, slack_max=10, capacity=10, fix_start_cumul_to_zero=True, name='Time' ) # Define the time windows for each location. for location_index, (start_time, end_time) in enumerate(time_windows): index = routing.NodeToIndex(location_index) time_dimension.CumulVar(index).SetRange(start_time, end_time) # Define the travel time callback. def travel_time_callback(from_index, to_index): from_node = routing.IndexToNode(from_index) to_node = routing.IndexToNode(to_index) return travel_times[from_node][to_node] transit_callback_index = routing.RegisterTransitCallback(travel_time_callback) # Set the cost of travel time. routing.SetArcCostEvaluatorOfAllVehicles(transit_callback_index) # Set 1 vehicle with unlimited capacity. routing.AddDimensionWithVehicleCapacity( 0, 0, [10], True, 'Capacity' ) # Solve the problem. search_parameters = pywrapcp.DefaultRoutingSearchParameters() search_parameters.first_solution_strategy = ( routing_enums_pb2.FirstSolutionStrategy.PATH_CHEAPEST_ARC ) solution = routing.SolveWithParameters(search_parameters) # Print the solution. index = routing.Start(0) while not routing.IsEnd(index): node = routing.IndexToNode(index) print('Location:', node) print('Time:', routing.CumulVar(index, 'Time').Min(), '-', routing.CumulVar(index, 'Time').Max()) index = solution.Value(routing.NextVar(index))tsp_with_time_windows()这个案例代码定义了4个城市的位置和时间窗口,以及它们之间的旅行时间。通过使用 Routing Solver 的 AddDimensionWithVehicleCapacity() 方法,我们为每个城市添加了一个时间维度,并设置了时间窗口。然后,通过调用 SolveWithParameters() 方法,我们可以求解问题并获得最优解。Google OR-Tools 提供了强大的功能,可以解决跨越多天并包含开始/停止时间的 TSP 问题。通过合理地定义城市的时间窗口和旅行时间,我们可以找到一条最短路径,使得旅行商能够在规定的时间内完成旅行。使用 OR-Tools 的 Routing Solver,我们可以轻松解决这个复杂的组合优化问题。Copyright © 2025 IZhiDa.com All Rights Reserved.
知答 版权所有 粤ICP备2023042255号