• python 贪婪算法


    贪婪算法

    覆盖问题,有个节目想要将自己的节目通过电台发布到几个州,这些电台可能互相有所覆盖,即覆盖了相同的州,现在如何能找到几个电台,最优的覆盖这些州。

    # 想要电台覆盖的州
    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_for_station in stations.items():
        covered = states_needed & states_for_station  # 两个集合的交集,也就是当前电台能覆盖几个我们想要覆盖的州
        if len(covered) > len(states_covered):  # 找出覆盖范围最大的那个电台,贪婪算法,每步都找最优解
          best_station = station
          states_covered = covered
    
      states_needed -= states_covered  # 找到一个电台,就将这个电台覆盖的州剔除掉
      final_stations.add(best_station)
    
    print(final_stations)
    
  • 相关阅读:
    idea自带的maven
    面试题汇总
    mybatis参数处理
    tips
    mybatis-config.xml
    helloWorld程序
    idea遇到的问题汇总
    PL/SQL批量执行SQL脚本文件
    Iframe跳转本地项目
    angular video播放问题
  • 原文地址:https://www.cnblogs.com/wztshine/p/13063764.html
Copyright © 2020-2023  润新知