Cs50 Tideman Solution ((free))
bool vote(int rank, string name, int ranks[]) { for (int i = 0; i < candidate_count; i++) { if (strcmp(name, candidates[i]) == 0) { ranks[rank] = i; return true; } } return false; } For a single voter’s ranks array, we need to update preferences[a][b] for every pair where a is preferred over b .
void sort_pairs(void) { for (int i = 0; i < pair_count - 1; i++) { for (int j = 0; j < pair_count - i - 1; j++) { int margin1 = preferences[pairs[j].winner][pairs[j].loser] - preferences[pairs[j].loser][pairs[j].winner]; int margin2 = preferences[pairs[j+1].winner][pairs[j+1].loser] - preferences[pairs[j+1].loser][pairs[j+1].winner]; if (margin1 < margin2) { pair temp = pairs[j]; pairs[j] = pairs[j+1]; pairs[j+1] = temp; } } } return; } This is where most students fail. We must lock pairs one by one, but before locking, check if the new edge would create a cycle. Cs50 Tideman Solution
int preferences[MAX][MAX]; bool locked[MAX][MAX]; string candidates[MAX]; int pair_count; int candidate_count; bool vote(int rank, string name, int ranks[]) {
: The problem requires that each pair appears only once, with the winner first. with the winner first.