"how numbers are stored and used in computers"
A vertex cover of an undirected graph is a set of vertices such that each edge of the graph is incident to at least one vertex in the set. The Minimum Vertex Cover (MVC) problem seeks to find a vertex cover of minimum size.
Given an undirected graph
The MVC problem is NP-hard for general graphs. However, it can be solved efficiently for some special classes of graphs:
A simple 2-approximation algorithm:
code.py1def approximate_vertex_cover(graph): 2 cover = set() 3 edges = list(graph.edges()) # Make a copy of edges 4 5 while edges: 6 # Pick any edge (u,v) 7 u, v = edges[0] 8 # Add both endpoints to cover 9 cover.add(u) 10 cover.add(v) 11 # Remove all edges incident to u or v 12 edges = [edge for edge in edges 13 if u not in edge and v not in edge] 14 15 return cover
For trees, we can use dynamic programming:
code.py1def mvc_tree(tree, root): 2 def dp(node, parent, must_cover): 3 if not tree[node]: 4 return 1 if must_cover else 0 5 6 if must_cover: 7 # Must include this node 8 return 1 + sum(dp(child, node, False) 9 for child in tree[node] if child != parent) 10 else: 11 # Try both including and excluding 12 include = 1 + sum(dp(child, node, False) 13 for child in tree[node] if child != parent) 14 exclude = sum(dp(child, node, True) 15 for child in tree[node] if child != parent) 16 return min(include, exclude) 17 18 return dp(root, None, False)
The MVC problem can be formulated as an integer linear program:
Where
The MVC problem is closely related to several other graph problems:
Exact Solution (Brute Force)
2-Approximation Algorithm
Dynamic Programming (Trees)
Where