Maya’s heart sank. She had been checking loser → X → winner . But what about loser → X → Y → winner ?
"Yes," Maya sighed. "I sort the pairs. Strongest first. Alice over Bob? Lock it. Bob over Charlie? Lock it. Charlie over Alice? Don't lock it because it creates a cycle. But my cycle detection is wrong."
Kai chuckled. "That's not just Tideman, Maya. That's life. Don't create cycles. Always check if the person you're stepping on has a hidden path back to you." Cs50 Tideman Solution
"Show me your cycle detection," Kai said.
He drew on the whiteboard:
In a directed graph, adding an edge from A → B creates a cycle if and only if B can already reach A.
Every year, the village of Coderidge held an election for the Keeper of the Orchard. Unlike other villages, they used a complex ranked voting system designed by a long-dead mathematician named Tideman. The rule was simple: if there was a way to trace a circle of preference (A beats B, B beats C, C beats A), that circle was a paradox, and the weakest link in that circle must be ignored. Maya’s heart sank
// Returns true if adding edge winner->loser creates a cycle bool creates_cycle(int winner, int loser) { // If the loser can reach the winner through existing locked edges, // then adding winner->loser would complete a cycle. return dfs(loser, winner); } bool dfs(int current, int target) { if (current == target) return true; for (int i = 0; i < candidate_count; i++) { if (locked[current][i] && dfs(i, target)) return true; } return false; }