贪婪算法就是每步都采取最优的做法。每步都选择局部最优解,最终得到的就是全局最优解。
#创建一个列表,其中包含要覆盖的州
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["kthree"]=set(['or','nv','ca'])
stations["kfour"]=set(['nv','ut'])
stations["kfive"]=set(['ca','az'])
#使用一个集合来存储最终选择的广播台
final_stations=set()
#选择覆盖最多的未覆盖的广播台存储到beat_station中
while states_needed:
best_station=None
states_covered=set()
for station,states in stations.items():
covered=states_needed & states
if len(covered)>len(states_covered):
best_station=station
states_covered=covered
states_needed-=states_covered
final_stations.add(best_station)
print(final_stations)
运行结果:
{'kthree', 'kfive', 'kone', 'ktwo'}