贪婪算法

3.集合覆盖问题

现在有个广播节目,需要让全美50个州的听众收听。每个广播台都覆盖特定的区域,不同广播台覆盖区域可能重叠。如何找出覆盖全美50个州的最小波广播台集合呢?

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()   # 最终选择的广播台
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

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)
4.NP完全问题

简单定义:需要计算所有的解,并从中选出最小/最短的那个。如旅行商问题和集合覆盖问题。
面对 NP 完全问题时,最佳做法时使用近似算法。
贪婪算法易于实现、运行速度快、是不错的近似算法。

你可能感兴趣的:(贪婪算法)