【发布时间】:2020-11-19 01:03:30
【问题描述】:
我一直在尝试解决 lock_pairs 函数的问题。我使用递归来验证我们是否有一条遵循循环的路径(基本上,遵循失败者的路径,看看它是否战胜了另一个候选人,并检查我们是否回到原点,有效地形成了一个循环)。
但是我遇到了一个问题,因为它在使用 check50 验证我的解决方案时返回错误,而且我太迷茫了,甚至都想不出哪里出了问题,我觉得我已经检查了所有内容,但仍然无法正常工作。
这是来自 check50 的错误:
:( lock_pairs skips final pair if it creates cycle
lock_pairs did not correctly lock all non-cyclical pairs
代码如下:
// To be used in lock_pairs to avoid cycles, true means cycles, false means we good
bool check_cycles(int loser_ind, int winner_ind)
{
// Base case, if the loser path returns to the winner, we have a circle
if (loser_ind == winner_ind)
{
return true;
}
for (int i = 0; i < candidate_count; i++)
{
if (locked[loser_ind][i]) // If the loser has an edge over another candidate, i.e, if the loser candidate won against another candidate
{
return check_cycles(i, winner_ind); // We'll check if that other candidate that lost has a winning path to another candidate
}
}
return false;
}
// Lock pairs into the candidate graph in order, without creating cycles
void lock_pairs(void)
{
// Let's loop on all pairs
for (int i = 0; i < pair_count; i++)
{
// If we didn't created a cycle, we'll register the lock
if (!check_cycles(pairs[i].loser, pairs[i].winner))
{
locked[pairs[i].winner][pairs[i].loser] = true; // It means the i-th pair winner candidate won over i-th pair losing candidate
}
}
return;
}
【问题讨论】:
-
你可以考虑锁定失败者索引,这样胜利者最后就没有锁了。您只需在最后一次锁定迭代时调用您的循环检查。 (在此之前,没有循环的可能性)。放置锁时,如果您初始化一个
int数组,其中pair_countelements 在开头全部为零,然后将值设置为array[pairs[i].loser] = 1并锁定每个边,您可以简单地检查是否只有一个索引保持为零,如果对应于下一个要放置的锁的索引——不要放置它。 (至少 PSET3 中的所有测试都这样) -
谢谢!!实际上,这有助于我更好地理解练习
-
很高兴它有帮助。如果您仍然遇到问题,请告诉我,我很乐意为您提供进一步帮助。