码迷,mamicode.com
首页 > 编程语言 > 详细

贪婪算法

时间:2018-11-09 11:27:59      阅读:211      评论:0      收藏:0      [点我收藏+]

标签:final   思路   nal   style   col   states   循环   int   集合   

要求是用最少的电台覆盖最多的州,每个电台所能覆盖的州不一样

算法思路:每次将所有集合和总集合求交集,留下交集len最长的哪个,再用总集合-留下集合进行下一轮循环,直到总集合为0

states = 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:
    best_stationname = None
    states_covered = set()
    #这里这个for,第一个是遍历的name,第二个遍历的是set
    for stationname, stationset in stations.items():
        covered = states & stationset
        if len(covered) > len(states_covered):
            best_stationname = stationname
            states_covered = covered
    states = states - states_covered
    final_stations.add(best_stationname)

print final_stations

 

贪婪算法

标签:final   思路   nal   style   col   states   循环   int   集合   

原文地址:https://www.cnblogs.com/j657521265/p/9933971.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!