8-20、贪婪算法
贪婪算法:
每步都采取最优的做法,你每步都选择局部最优解,最终得到的就是全局最优解。
##创建一个列表,其中包含要覆盖的州 states_needed = set(["mt", "wa", "or", "id", "nv", "ut", "ca", "az"]) stations = {} stations["kone"] = set(["id", "nv", "ut"]) stations["ktwo"] = set(["wa", "id", "mt"]) stations["kthres"] = set(["or", "nv", "ca"]) stations["kfour"] = set(["nv", "ut"]) stations["kfive"] = set(["ca", "az"]) #使用一个集合来存储最终选择的广播台 final_stations = set() while states_needed: best_station = None states_covered = set() for station, states_for_station in stations.items(): covered = states_needed & states_for_station if len(covered) > len(states_covered): best_station = station states_covered = covered states_needed -= states_covered final_stations.add(best_station) print(final_stations)
本文来自博客园,作者:hematologist,转载请注明原文链接:https://www.cnblogs.com/littleMa/p/9509030.html
posted on 2018-08-21 01:01 hematologist 阅读(222) 评论(0) 编辑 收藏 举报