简体   繁体   中英

Flaw in lock_pairs function in CS50's Tideman problem set

Could someone please point out what the flaw with my logic is? It'd be much appreciated.

Basically, what I'm trying to do with the nested loops is to check if the loser of any pair has been a winner in a previous pair (with higher strength of victory). If yes, I then move onto the inner loop to check if the winner of the pair has been a loser in any of the previous pairs thereby creating a cycle. Does my understanding of what constitutes a cycle is even right? How can I rectify this without implementing recursion? I can't figure out how to do it.

void lock_pairs(void)
{
    
  bool cycleCheck = false;
  
  for (int u = 0; u < pair_count; u++)
  {
  
   for (int m = 0; m < u; m++)
   {
    if (pairs[u].loser == pairs[m].winner)
    {
        for (int k = m; k < u; k++)
        {
        if (pairs[u].winner == pairs[k].loser)
        {
            locked[pairs[u].winner][pairs[u].loser] = false;
            cycleCheck = true;
        }
        }
    }
   }
  
  
  if (cycleCheck == false)
  {
      locked[pairs[u].winner][pairs[u].loser] = true;
  }
  
  cycleCheck = false;
  
  }
      
}

Given a pair A beats B, to check for a cycle you should iterate over all pairs looking for B as a winner. Then, for each candidate who lost to B, you should iterate over all pairs looking for this candidate as a winner. Then, for each candidate who lost to this candidate... you got it. If, at any time, A appears, it is a cycle.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM