# 包含所有州的集合
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()
# 反复循环直到需要的州变成0,以需要覆盖的州为循环条件
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
final_stations.add(best_station) # 最佳电台放到最终选择电台的集合中
# 更新需要的州
states_needed -= states_covered
print(final_stations)
{‘kthree’, ‘ktwo’, ‘kfive’, ‘kone’}