📜  约瑟夫斯问题| (迭代解决方案)

📅  最后修改于: 2021-05-06 22:51:43             🧑  作者: Mango

有N个孩子坐在围绕一个圆圈排列的N个椅子上。椅子的编号是从1到N。游戏从第一个椅子开始盘旋地盘算着孩子们。一旦计数达到K,那个孩子就离开游戏,移开他/她的椅子。游戏再次开始,从圈子中的下一个椅子开始。圈子中剩下的最后一个孩子是获胜者。找到赢得比赛的孩子。

例子:

Input : N = 5, K = 2
Output : 3
Firstly, the child at position 2 is out, 
then position 4 goes out, then position 1
Finally, the child at position 5 is out. 
So the position 3 survives.

Input : 7 4
Output : 2

我们讨论了约瑟夫斯问题的递归解。给定的解决方案优于Josephus解决方案的递归解决方案,后者不适合大输入,因为它会导致堆栈溢出。时间复杂度为O(N)。

方法–在算法中,我们使用sum变量找出要删除的椅子。当前的椅子位置是通过将椅子数量K加到先前的位置(即总和和总和模数)来计算的。最后,当编号从1开始到N时,我们返回sum + 1。

C++
// Iterative solution for Josephus Problem 
#include 
using namespace std;
  
// Function for finding the winning child.
long long int find(long long int n, long long int k)
{
    long long int sum = 0, i;
  
    // For finding out the removed 
    // chairs in each iteration
    for (i = 2; i <= n; i++)
        sum = (sum + k) % i;
  
    return sum + 1;
}
  
// Driver function to find the winning child
int main()
{
    int n = 14, k = 2;
    cout << find(n, k);
    return 0;
}


Java
// Iterative solution for Josephus Problem
class Test 
{
  
    // Method for finding the winning child.
    private int josephus(int n, int k) 
    {
        int sum = 0;
  
        // For finding out the removed 
        // chairs in each iteration 
        for(int i = 2; i <= n; i++) 
        {
            sum = (sum + k) % i;
        }
  
        return sum+1;
    }
  
    // Driver Program to test above method 
    public static void main(String[] args)
    { 
        int n = 14; 
        int k = 2; 
        Test obj = new Test();
        System.out.println(obj.josephus(n, k)); 
    }
}
  
// This code is contributed by Kumar Saras


输出:
13