关于 算法图解 ,贪婪算法,广播台覆盖问题,
代码参考
http://makaidong.com/lilong117194/1/1015033_11095410.html
感谢上面的兄弟。
打印输出很多,主要是看看程序走到哪里,
想到了一个优化,多了一行,,灵感主要来自,吴军 老师讲解的“少做事”。吴军,吴军。
# coding=utf-8
# 要覆盖的州
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() # 存储最终选择的广播台
print('start1234')
while states_needed: # 只要没有全部覆盖完
best_station = None
states_covered = set() # 存储已经覆盖的州
for station, states in stations.items(): # items()存储键值(广播台和相应的覆盖州)
print(station)
print(states)
print('balabala')
covered = states_needed & states # 集合的交集,判断还未覆盖的州与此广播台的交集个数
if len(covered) > len(states_covered): # 如果当前广播台州交集的个数大于当前要覆盖的州
print(len(covered))
print('jinruneibu88888888888888888888888888888888888')
best_station = station # 就替换为最优的广播台
states_covered = covered # 替换已经覆盖的州
states_needed -= states_covered # 从要覆盖的州中减去已经覆盖过的(集合相减)
print 'states_needed:',states_needed
final_stations.add(best_station) # 添加最优的广播台
print(best_station)
#--------------------------------------------每次将字典的规模变小
del stations[best_station] #想到的一点,改进,既然已经晋级,就不要再参加PK ,
print final_stations
result
$python main.py
start1234
kfive
set(['ca', 'az'])
balabala
2
jinruneibu88888888888888888888888888888888888
ktwo
set(['mt', 'id', 'wa'])
balabala
3
jinruneibu88888888888888888888888888888888888
kthree
set(['ca', 'or', 'nv'])
balabala
kone
set(['ut', 'id', 'nv'])
balabala
kfour
set(['ut', 'nv'])
balabala
states_needed: set(['ut', 'ca', 'az', 'or', 'nv'])
ktwo
kfive
set(['ca', 'az'])
balabala
2
jinruneibu88888888888888888888888888888888888
kthree
set(['ca', 'or', 'nv'])
balabala
3
jinruneibu88888888888888888888888888888888888
kone
set(['ut', 'id', 'nv'])
balabala
kfour
set(['ut', 'nv'])
balabala
states_needed: set(['ut', 'az'])
kthree
kfive
set(['ca', 'az'])
balabala
1
jinruneibu88888888888888888888888888888888888
kone
set(['ut', 'id', 'nv'])
balabala
kfour
set(['ut', 'nv'])
balabala
states_needed: set(['ut'])
kfive
kone
set(['ut', 'id', 'nv'])
balabala
1
jinruneibu88888888888888888888888888888888888
kfour
set(['ut', 'nv'])
balabala
states_needed: set([])
kone
set(['ktwo', 'kthree', 'kone', 'kfive'])
请高手帮忙解答一下,优化后,和优化前,算法的复杂度,有无变化? 各位大神,求指教。