贪婪算法
试图从局部最优解得到全局最优解,旅行商问题和覆盖问题都是典型的NP问题。
下面是电台覆盖的问题:
1、首先选择能覆盖最多州的电台。
2、从剩下的电台里面找到在剩下的未覆盖的州能覆盖最多的电台
3、循环上面步骤,直到所有的州都被电台覆盖,即使有的州被重复覆盖
# 贪婪算法,先选取众多选择里面最好的,然后从剩下的里面选择最好的,直到到达基线条件
states_needed = set(['mt', 'wa', 'or', 'id', 'ca', 'ut'])
stations = {}
stations['kone'] = set(['id', 'nv', 'ut'])
stations['ktwo'] = set(['wa', 'id', 'mt'])
stations['kthree'] = set(['or', 'nv', 'ca'])
select_stations = set()
def tanlan(states_needed, stations):
while len(states_needed) > 0: # 基线条件,也就是停止循环的条件
lagerest_station = None
covert_states = set()
for n, states in stations.items():
covered = states & states_needed
if len(covered) > len(covert_states): # 循环条件,当前的交集大于上一个交集就时循环
lagerest_station = n
covert_states = covered
select_stations.add(lagerest_station)
states_needed -= covert_states
del stations[lagerest_station]
print(lagerest_station)
print(tanlan(states_needed, stations))