首页 > 解决方案 > CS50 Pset 3 Tideman 的 Lock_pair 函数 - 检查图中的循环

问题描述

我正在研究一个名为潮人的问题。目标是制作一个遵循潮人算法的投票程序。这是对问题的解释:https ://cs50.harvard.edu/x/2020/psets/3/tideman/Check50(我正在学习的 CS50 课程中提供的测试)总是返回“lock_pairs 如果它创建一个循环则跳过中间对。lock_pairs 没有正确锁定所有非循环对” lock_pairs 函数的目的是查看图表赢家和输家,并确保没有创建一个循环(问题的链接更好地解释了它)。我不完全理解跳过中间对意味着什么,并且该程序在我测试它时创建一个循环的情况下工作。此外,它通过了检查“lock_pairs 如果它创建循环则跳过最终对”。我通过检查所有候选者是否都有边缘(忽略该对的当前失败者)来实现 lock_pairs,并且仅在并非所有候选者都有边缘时才锁定该对(因此不创建循环)。我该如何解决?

void lock_pairs(void)
{
    //checks if a candidate has an edge on it, originally sets all to 0
    bool candidatesEdge[candidate_count];

    for(int i = 0; i < candidate_count; i ++)
    {
        candidatesEdge[i] = false;
    }

    for (int i = 0; i < pair_count; i ++)
    {
        //variable to see if all others have edges
        bool full = true;
        int j = 0;

        //checks through all other candidates for an edge
        while (j < candidate_count && full == true)
        {
            //if a candidate besides the current being checked doesn't have an edge, full is false
            if (j != pairs[i].loser && candidatesEdge[j] == false)
            {
                full = false;
            }

            j++;
        }

        //if not all candidates have edges, gives the loser of the pair an edge
        if (full == false)
        {
            candidatesEdge[pairs[i].loser] = true;
            locked[pairs[i].winner][pairs[i].loser] = true;
        }
    }
}

标签: ccyclecs50

解决方案


推荐阅读