贪婪算法:每步都采取最优的做法,最终得到的就是全局最优解
"""
贪婪算法
覆盖所有的州,最小集合
方法:
(1)选出一个广播,它覆盖了最多的未覆盖州,即便广播台覆盖了一些已经覆盖的州,也没有关系
(2)重复第一步,知道所有的州都被覆盖
"""
states_needed = set(['mt', 'wa', 'or', 'id', 'nv', 'ut', 'ca', 'az'])
stations = {
'kone': set(['id', 'nv', 'ut']), # kone 覆盖这些州
'ktwo': set(['wa', 'id', 'mt']),
'kthree': set(['or', 'nv', 'ca']),
'kfour': set(['nv', 'ut']),
'kfive': set(['ca', 'az'])
}
best_result = []
final_states = set()
while states_needed:
best_station = None
best_states = set()
for station, states in stations.items():
covered = states_needed & states
if len(covered) > len(best_states):
best_station = station
best_states = covered
best_result.append(best_station)
states_needed -= best_states
final_states |= best_states
print(best_result) # ['kone', 'ktwo', 'kthree', 'kfive']