Here’s a helper function idea:

// Returns true if there is a path from start to end in locked graph
bool creates_cycle(int start, int end)
if (start == end)
        return true;
for (int i = 0; i < candidate_count; i++)
if (locked[start][i] && creates_cycle(i, end))
        return true;
return false;

In lock_pairs():

Why loser → winner in the check? Because we already have edges in direction of winner → loser. If loser can reach winner, adding winner → loser closes the cycle.


The Tideman voting method works like this:


The goal here is to sort the pairs of candidates based on the strength of their victory. The stronger the win, the higher the rank.

The Mistake: My first instinct was to use a simple sorting algorithm (like bubble sort) on the pairs array. But I kept getting the order wrong. I was trying to sort the candidates themselves, rather than the magnitude of the margin.

The Solution: You have to look at preferences[i][j]. The key realization is that you aren't just sorting numbers; you are sorting structs based on numbers.

A Comprehensive Analysis of the CS50 Solution

The beginning is deceptively easy. You have to record preferences. If Alice beats Bob, Alice gets a point. Simple array work. I thought, "Hey, this isn't so bad."

Then came the graph.