本文是在上次的基礎上做的優化,解決了窮舉結果的尷尬
文章鏈接:Python3 回朔法解決作業分配問題(http://blog.csdn.net/liangxun0712/article/details/70598467)
廢話不多說,直接上優化後的代碼
class Worker: max = 0 # 上界 通過貪心算法找出近似值 min = 0 # 下界 由每組的最小值組成 pt_nodes = [] # 存放可擴展的節點 input_file = '' # 輸入文件名 output_file = '' # 輸出文件名 matrix = [] # 存放數據矩陣 行爲單個任務 每個工人 完成所要的時間 n = 0 # 數據矩陣的大小 n*n min_cost = 10000 worker_mark = [] # 標記工人是否被分配了任務 # 初始化參數 def __init__(self, input_file, output_file): self.input_file = input_file self.output_file = output_file self.read_data_from_file() self.n = len(self.matrix) self.get_low_limit() self.get_up_limit() print(self.matrix) print(self.n) print(self.max) print(self.min) # 從文件中讀取數據 初始化數據矩陣 def read_data_from_file(self): with open(self.input_file) as source: for line in source: data_cluster = line.split(',') temp = [] for value in data_cluster: temp.append(int(value)) self.matrix.append(temp) # 獲取數據下界 最小值之和 def get_low_limit(self): for i in range(self.n): self.min += min(self.matrix[i]) # 獲取數據上界 貪心算法 def get_up_limit(self): # 初始化工人使用標記 worker_mark = [] for i in range(self.n): worker_mark.append(0) # 貪心算法 取得 近似最優解 for i in range(self.n): temp = self.matrix[i] min_value = 5000 index = 0 for k in range(self.n): if worker_mark[k] == 0 and min_value > temp[k]: min_value = temp[k] index = k worker_mark[index] = 1 # 標記工人是否被分配 self.max += min_value # 累積上限值 # 初始化工人分配標記 def init_worker(self): self.worker_mark = [] for i in range(self.n): self.worker_mark.append(0) # 剪枝優化後的回朔算法 def branch_limit(self, deep, total): if deep == self.n: # print('最短距離', total) if self.min_cost > total: self.min_cost = total return temp = self.matrix[deep] for i in range(self.n): if self.worker_mark[i] == 0: if (temp[i] + total) > self.max: # 超出上界的節點直接捨棄 continue else: self.worker_mark[i] = 1 self.branch_limit(deep+1, total+temp[i]) self.worker_mark[i] = 0 input_file = 'input_assign05_01.dat' # input_file = 'input_assign05_02.dat' # input_file = 'input_assign05_03.dat' output_file = 'output_01.dat' # output_file = 'output_02.dat' # output_file = 'output_03.dat' worker = Worker(input_file, output_file) worker.init_worker() worker.branch_limit(0, 0) print(worker.min_cost)