贪婪算法
Posted j657521265
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了贪婪算法相关的知识,希望对你有一定的参考价值。
要求是用最少的电台覆盖最多的州,每个电台所能覆盖的州不一样
算法思路:每次将所有集合和总集合求交集,留下交集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
以上是关于贪婪算法的主要内容,如果未能解决你的问题,请参考以下文章