import networkx as nx# 创建一个空的图对象G = nx.Graph()# 添加国家节点countries = ['中国', '哈萨克斯坦', '俄罗斯', '白俄罗斯', '波兰', '德国', '法国', '西班牙']for country in countries: G.add_node(country)# 添加班列边及其属性G.add_edge('中国', '哈萨克斯坦', distance=3000, time=5, capacity=1000, goods='工艺品、饮品、玩具')G.add_edge('哈萨克斯坦', '俄罗斯', distance=2000, time=3, capacity=800, goods='工艺品、饮品、玩具')G.add_edge('俄罗斯', '白俄罗斯', distance=500, time=1, capacity=600, goods='工艺品、饮品、玩具')G.add_edge('白俄罗斯', '波兰', distance=800, time=2, capacity=700, goods='工艺品、饮品、玩具')G.add_edge('波兰', '德国', distance=1000, time=2, capacity=900, goods='工艺品、饮品、玩具')G.add_edge('德国', '法国', distance=1000, time=2, capacity=800, goods='工艺品、饮品、玩具')G.add_edge('法国', '西班牙', distance=1500, time=4, capacity=1000, goods='工艺品、饮品、玩具')# 查询所有班列的相关信息for edge in G.edges(): start, end = edge distance = G.edges[edge]['distance'] time = G.edges[edge]['time'] capacity = G.edges[edge]['capacity'] goods = G.edges[edge]['goods'] print(f'{start}到{end}:距离{distance}公里,耗时{time}天,载货量{capacity}吨,货物类型为{goods}')# 根据企业的货运需求推荐班列信息def recommend_routes(origin, destination, weight): routes = nx.all_simple_paths(G, origin, destination) recommended_route = None min_time = float('inf') min_cost = float('inf') for route in routes: total_time = 0 total_cost = 0 for i in range(len(route)-1): edge = (route[i], route[i+1]) total_time += G.edges[edge]['time'] total_cost += G.edges[edge]['distance'] * weight * 10 # 假设运费为每公里每吨10元 if total_time < min_time: min_time = total_time min_cost = total_cost recommended_route = route elif total_time == min_time and total_cost < min_cost: min_cost = total_cost recommended_route = route return recommended_route, min_time, min_cost# 使用示例origin = '中国'destination = '西班牙'weight = 100route, time, cost = recommend_routes(origin, destination, weight)print(f'推荐路线:{route},总耗时{time}天,总费用{cost}元')
这只是一个基本的代码示例,根据实际需求可以进一步完善和优化。希望能帮到你!