Set covering problem with the greedy algorithm

Thought the greedy algorithm: each step select local optimal solution is to finally get global optimal solution.

Approximation algorithm: long time is required to obtain exact solutions can be used approximation algorithm.

Analyzing approximation algorithm criteria:

The addition of fast speed;

Approximate solution obtained with the proximity of the optimal solution;

Greedy algorithm is a good choice, not only simple, but typically runs very quickly.

Set operations:

Their union: setA | setB

Intersection operator: setA & setB

Set difference operation: setA - setB

Collection does not contain duplicate elements;

Most coverage area with a minimum of a broadcasting station, a different broadcasting station coverage areas may overlap problem:

DEF Greedy (states_needed): 
# stores the final selection of the broadcasting station
final_stations = the SET ()

the while states_needed:
# storage covers most of the uncovered state broadcasting station
best_station = None
# include all states not covered by the radio station covered, for loop iteration each broadcast station, and determine whether it is the best radio station
states_covered = the SET ()
# iterate through all of the broadcast stations
for station, States in stations.items ():
# seek to be covered with a collection of stations broadcasting station covering the intersection of state collections
covered's = states_needed States &
# each time to find a radio station covering most of the state
IF len (covered's)> len (states_covered):
# save the current radio station
best_station = station
# save the current set of states covered
= covered's states_covered
# update the set of states to be covered
states_needed -= states_covered
# 将找出的广播台添加到最终集合
final_stations.add(best_station)

# print(final_stations)
return final_stations


if __name__ == '__main__':

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"])
print(greedy(states_needed))

 

Guess you like

Origin www.cnblogs.com/songyuejie/p/11422543.html