Cs50 Tideman Solution

Cs50 Tideman Solution -

Maya submitted her solution. And in the real election that followed, Alice became Keeper of the Orchard—not because she was the strongest in every head-to-head match, but because when paradoxes arose, the village had a coder wise enough to know which locks to leave open. Don't just check for a two-step loop. Use depth-first search to see if the loser has any path to the winner in the existing locked graph. If yes, skip the pair. That’s the entire secret of Tideman.

// 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; }

Maya pointed. "I wrote a recursive function creates_cycle(winner, loser) . It checks if the loser has any locked edges pointing to another candidate. Then it checks if that candidate points back to the original winner. If yes, it’s a cycle."

Kai nodded slowly. "You are looking for a direct path back to the winner. But what if the path is three steps? Four? Your recursion only goes two levels deep." Cs50 Tideman Solution

Maya was the new programmer tasked with tabulating the votes. She had the first part down: counting each ballot to build a 2D array of preferences . It told her that Alice beat Bob (5 votes to 2), Bob beat Charlie (4 to 3), and Charlie beat Alice (3 to 2). A perfect, frustrating cycle.

He drew on the whiteboard:

Her friend, an old sysadmin named Kai, peered over her shoulder. "You're trying to lock every pair in order of strength, right?" Maya submitted her solution

Maya’s heart sank. She had been checking loser → X → winner . But what about loser → X → Y → winner ?

"Show me your cycle detection," Kai said.

Her job was to "lock in" the strongest edges of victory to create a directed graph of the winner—without creating a cycle. Use depth-first search to see if the loser

"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."

The story is useful because the narrative (the cycle, the DFS, the "path back") sticks in your brain longer than any pseudocode. Next time you face Tideman, remember Maya and the Orchard.

"It's not about the edge you're adding," she whispered. "It's about the path that already exists beneath it."