Greedy APX Algorithm for min Vertex Cover @input: graph (graph stored in an adjacency list where each vertex is represented with an integer) @example: >>> graph = {0: [1, 3], 1: [0, 3], 2: [0, 3, 4], 3: [0, 1, 2], 4: [2, 3]} >>> greedy_min_vertex_cover(graph) {0,
(graph: dict)
| 10 | |
| 11 | |
| 12 | def greedy_min_vertex_cover(graph: dict) -> set[int]: |
| 13 | """ |
| 14 | Greedy APX Algorithm for min Vertex Cover |
| 15 | @input: graph (graph stored in an adjacency list where each vertex |
| 16 | is represented with an integer) |
| 17 | @example: |
| 18 | >>> graph = {0: [1, 3], 1: [0, 3], 2: [0, 3, 4], 3: [0, 1, 2], 4: [2, 3]} |
| 19 | >>> greedy_min_vertex_cover(graph) |
| 20 | {0, 1, 2, 4} |
| 21 | """ |
| 22 | # queue used to store nodes and their rank |
| 23 | queue: list[list] = [] |
| 24 | |
| 25 | # for each node and his adjacency list add them and the rank of the node to queue |
| 26 | # using heapq module the queue will be filled like a Priority Queue |
| 27 | # heapq works with a min priority queue, so I used -1*len(v) to build it |
| 28 | for key, value in graph.items(): |
| 29 | # O(log(n)) |
| 30 | heapq.heappush(queue, [-1 * len(value), (key, value)]) |
| 31 | |
| 32 | # chosen_vertices = set of chosen vertices |
| 33 | chosen_vertices = set() |
| 34 | |
| 35 | # while queue isn't empty and there are still edges |
| 36 | # (queue[0][0] is the rank of the node with max rank) |
| 37 | while queue and queue[0][0] != 0: |
| 38 | # extract vertex with max rank from queue and add it to chosen_vertices |
| 39 | argmax = heapq.heappop(queue)[1][0] |
| 40 | chosen_vertices.add(argmax) |
| 41 | |
| 42 | # Remove all arcs adjacent to argmax |
| 43 | for elem in queue: |
| 44 | # if v haven't adjacent node, skip |
| 45 | if elem[0] == 0: |
| 46 | continue |
| 47 | # if argmax is reachable from elem |
| 48 | # remove argmax from elem's adjacent list and update his rank |
| 49 | if argmax in elem[1][1]: |
| 50 | index = elem[1][1].index(argmax) |
| 51 | del elem[1][1][index] |
| 52 | elem[0] += 1 |
| 53 | # re-order the queue |
| 54 | heapq.heapify(queue) |
| 55 | return chosen_vertices |
| 56 | |
| 57 | |
| 58 | if __name__ == "__main__": |
no test coverage detected