欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

8.贪婪算法

程序员文章站 2022-05-23 09:58:59
...
# 最少的电台数,覆盖最多的州
# 需要覆盖的州的集合
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()

# 每次循环,选出能覆盖最多未选中的州的电台
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)