Sub topic 10
Modelling Real Problems as Bipartite Graphs
This chapter assumes you know the two-colouring algorithm from the earlier chapters and can read a Python adjacency list. Its subject is the step before you run any algorithm: deciding what the vertices and edges are.
Two Ways Bipartite Graphs Show Up
Real problems produce bipartite graphs in two different ways. Mixing them up is the most common modelling error.
| Situation | Where the two sides come from | Do you need to test bipartiteness? |
|---|---|---|
| Assignment | The problem gives two kinds of object: workers and jobs, students and courses, users and items | No. Every edge joins one kind to the other, so the graph is bipartite by construction |
| Conflict splitting | There is one kind of object, and some pairs must be kept apart | Yes. Two-colouring finds the split, or shows that none exists |
Assignment graphs
In an assignment graph, each vertex belongs to one of two named groups. Edges mean "can be paired with". A worker vertex links to every job that worker is qualified for. No edge ever joins two workers, so you already know the bipartition. Running a bipartiteness test here wastes time. The interesting questions come later, such as how many pairs you can make at once. That question is called matching, and a later chapter covers it.
Conflict graphs
In a conflict graph, all vertices are the same kind of object, and an edge means "these two must not be in the same group." Typical examples:
- Split a class into two teams so that no rivals share a team.
- Put exams into two time slots so that no student has two exams at once. Here an edge joins two exams that share a student.
- Assign two radio frequencies so that nearby transmitters differ.
A valid split into two groups is exactly a proper two-colouring. If the graph contains an odd cycle, no split exists, however you rearrange the groups.
A Worked Example: Splitting Rivals into Teams
The input uses names, so the code first maps each name to an index and then builds an undirected adjacency list. Each rivalry gets added in both directions.
from collections import deque
def split_into_two(people, rivalries):
"""Return two teams with no rivals together, or None if impossible."""
index = {name: i for i, name in enumerate(people)}
adj = [[] for _ in people]
for a, b in rivalries:
if a == b:
return None # someone in conflict with themselves can never be placed
adj[index[a]].append(index[b])
adj[index[b]].append(index[a])
colour = [-1] * len(people)
for s in range(len(people)):
if colour[s] != -1:
continue
colour[s] = 0
queue = deque([s])
while queue:
u = queue.popleft()
for v in adj[u]:
if colour[v] == -1:
colour[v] = 1 - colour[u]
queue.append(v)
elif colour[v] == colour[u]:
return None
teams = ([], [])
for name, c in zip(people, colour):
teams[c].append(name)
return teams
people = ["Ana", "Ben", "Cai", "Dee", "Eve"]
rivalries = [("Ana", "Ben"), ("Ben", "Cai"), ("Cai", "Dee"), ("Eve", "Ana")]
print(split_into_two(people, rivalries))
# (['Ana', 'Cai'], ['Ben', 'Dee', 'Eve'])
rivalries.append(("Dee", "Eve"))
print(split_into_two(people, rivalries))
# NoneThe last rivalry closes the cycle Ana, Ben, Cai, Dee, Eve, Ana. That cycle has five edges. Five is odd, so no two-team split exists.
Common Modelling Errors
- Edges with the wrong meaning. In a conflict graph, edges must mean "must differ." If you add edges for "get along well," the colouring will split up friends.
- Directed relationships. "Ana dislikes Ben" may be one-sided, but the constraint still applies to both people. Add the edge in both directions.
- Self-conflicts. A self-loop is a cycle of length 1, which is odd, so no colouring can satisfy it. Decide whether such input is an error or should be rejected outright.
- Isolated vertices. A person with no rivals still needs a team. Loop over every vertex, not only the ones that appear in edges.
- Hidden constraints. "Each team needs at least two people" or "teams must be equal in size" go beyond two-colouring. The colouring only guarantees that no edge sits inside one group. Balance needs more work, for example choosing which side of each component goes where.
Exercise
Exams A, B, C and D must fit into two time slots. Student 1 takes A and B, student 2 takes B and C, student 3 takes C and A, and student 4 takes D only. Build the conflict graph and decide whether two slots are enough.
Show answer
Join two exams when a student takes both. That gives edges A–B, B–C and C–A, and D is isolated. A, B and C form a triangle, an odd cycle of length 3, so the graph is not bipartite and two slots are not enough. D can go in either slot.
Exercise
A website records which users bought which products. Should you run a bipartiteness test on the user–product graph?
Show answer
No. Every edge joins a user to a product, so the graph is bipartite by construction, with users on one side and products on the other. Testing it tells you nothing new.