Tideman算法自定义循环检测逻辑无法通过check50的原因咨询
为何该算法无法检测循环?
// Lock pairs into the candidate graph in order, without creating cycles void lock_pairs(void) { // array[0] being true means that there is an edge or more pointing at candidate number 0 bool array[candidate_count]; for (int l = 0; l < pair_count; l++) { // add an edge, as long as it doesn't make a cycle if (!will_cycle(array, pairs[l].loser)) { locked[pairs[l].winner][pairs[l].loser] = true; array[pairs[l].loser] = true; } } } // index is the index of the candidate the edge will be pointing at if it's added // the function temporarily sets array[index] as true, like there's an edge pointing at it // the function then iterates over all the array array, if they're all true it means there'll be a cycle. // so it's undo the array[index] to false again. // and if there's at least one false in the array array, it means there won't be a cycle bool will_cycle(bool array[], int index) // return true if it will make a cycle { array[index] = true; int flag = 0; // var for number of true candidates for (int i = 0; i < candidate_count; i++) { if (array[i]) flag++; } if (flag == candidate_count) // they're all true { array[index] = false; return true; } return false; }
我认为图中的循环意味着不存在源点(源点指没有入边的候选者),因此当array数组全为true时,所有候选者都有至少一条入边,即存在循环。
为何该逻辑无法通过check50中关于lock_pair跳过会导致循环的边的测试?我自测时该逻辑运行正常,为何必须使用DFS这类算法?
我测试了CS50官网pset页面背景中的Alice、Charlie和Bob的例子,跟踪后发现算法正确跳过了最后一条会导致循环的边,且能得出正确的获胜者。
内容的提问来源于stack exchange,提问作者Eyad Ayman
相关产品推荐
相关产品推荐

