華爲軟件精英挑戰賽總結(初賽)算法
賽題:app
評分標準:負載均衡
思路:這是一個典型的動態負載均衡算法的設計,對於每一輛車來講,時間最短意味着路程最優,首先想到迪傑斯特拉來求出每一輛車的最優路徑。dom
1 def Dijkstra(Map, start_point, end_point): 2 dict = defaultdict(list) 3 for StartPoint,EndPoint,RoadLength in Map: 4 dict[StartPoint].append((RoadLength,EndPoint)) 5 q, seen, mins = [(0, start_point, ())], set(), {start_point: 0} 6 while q: 7 (cost,v1,path) = heappop(q) 8 if v1 not in seen: 9 seen.add(v1) 10 path = (v1, path) 11 if v1 == end_point: 12 break; 13 for RoadLength, v2 in dict.get(v1, ()): 14 if v2 in seen: continue 15 prev = mins.get(v2, None) 16 next = cost + RoadLength 17 if prev is None or next < prev: 18 mins[v2] = next 19 heappush(q, (next, v2, path)) 20 return cost,path
這是一個利用棧來優化後的迪傑斯特拉算法,算法返回路徑花費和具體路徑。這樣能求出每一輛車在地圖上的花費和最優路徑。函數
核心思想有了,能夠來處理數據,咱們利用pandas來進行數據的處理和儲存,處理後的數據得出三個矩陣,分別爲車輛,道路和交叉路口。優化
咱們利用路網信息來構建交通地圖:spa
1 def ConstructionMap(roadData): 2 Map = [] 3 for i in range(len(roadData)): 4 if (roadData[i][-1] == 1): 5 Map.append((str(roadData[i][-3]), str(roadData[i][-2]), roadData[i][1])) 6 Map.append((str(roadData[i][-2]), str(roadData[i][-3]), roadData[i][1])) 7 else: 8 Map.append((str(roadData[i][-3]), str(roadData[i][-2]), roadData[i][1])) 9 return Map
地圖Map中,有一個判斷語句,if (roadData[i][-1] == 1):,這句是判斷道路是否爲雙向道路,若是是雙向道路,則將信息添加到對稱位置中。因而可知Map矩陣在存儲雙向道路時,爲一個對稱矩陣。每一條信息存儲爲道路的起始信息和道路長度。設計
路網構建好後,就來到了核心算法,爲路網上的每個車輛尋找最優路線,達到全局最優,在這裏會出現思索的狀況,要根據具體狀況來斷定,解除死鎖。這是優化本題的關鍵。code
1 def FindRoute(CarList, RoadList, Map): 2 carRoute = [] 3 for carNum in range(len(CarList)): 4 ShortestRoute_theory = Dijkstra(Map, str(CarList[carNum][1]), str(CarList[carNum][2])) 5 ShortestRoute_list = [] 6 ShortestRoute_list.append(int(ShortestRoute_theory[0])) 7 lengthSumarize = len(ShortestRoute_list) 8 carRouteTmp = [CarList[carNum][0]] 9 carRouteTmp.append(CarList[carNum][-1]+random.randint(0,3000)) 10 for i in range(1, lengthSumarize - 1): 11 for j in range(len(RoadList)): 12 if ((RoadList[j][-3] == ShortestRoute_list[lengthSumarize - i] and RoadList[j][-2] == ShortestRoute_list[lengthSumarize - i - 1]) or (RoadList[j][-2] == ShortestRoute_list[lengthSumarize - i] and RoadList[j][-3] == ShortestRoute_list[lengthSumarize - i - 1])): 13 carRouteTmp.append(RoadList[j][0]) 14 carRoute.append(tuple(carRouteTmp)) 15 return carRoute
咱們將車列表,路列表和Map做爲函數的輸入,循環車列表,將列中的每輛車信息按照發車時間放入到路網中求解。可是,這樣作就會出現死鎖,由於在有限的路網信息中,隨着車數量的增長會出現某條道路上的車循環等待的狀況,這樣致使系統沒法繼續下去。咱們從死鎖的緣由入手,經過隨機數延長汽車的發車時間來緩解死鎖狀況。最後求出每一輛車的最優路線和時間。blog