如何解决约瑟夫问题?

本文详细介绍了约瑟夫问题的背景及其解决方案。采用环形单链表数据结构,结合具体的算法流程,实现了从指定起点开始计数,每数到特定数值则移除相应节点直至只剩一个节点的过程。

1.Josephu问题

问题介绍:

设编号为1,2,3...n的n个人围坐一圈,约定编号为k(1<=k<=n)的人从1开始报数,数到m的那个人出列,它的下一位又从1开始报数,数到m的那个人出列,依次类推

 

如何解决约瑟夫问题?

构建环形链表+处理算法

 

思路:
使用一个不带头结点的循环链表来处理问题,先构成一个有n个结点的单循环链表,然后由k结点起从1开始计数,计到m的时候 对应结点从链表中删除,然后再从被删除节点的下一个从1开始计数,直到最后一个节点删除,算法结束

 

示意图:

k         编号为k的人开始报数

令n=5 说明有5个人

令k=1 说明从第一个人开始报数

令m=2说明每数两下就出圈1次

出队列顺序:2-->4-->1-->5-->3

代码实现:


1.构建环形链表:

*先创建第一个节点,创建first指向该节点,并形成环状

*后面当我们每创建一个新的节点,就把该节点加到现有的环形链表中

2.遍历环形链表

*先让一个辅助指针指向first

*然后通过while循环进行循环遍历该节点,直到遍历的下一个为first,遍历结束

public class Josepfu {
    public static void main(String[] args) {
        //测试一:环形链表

        CircleSingleLinkedList circleSingleLinkedList=new CircleSingleLinkedList();
        circleSingleLinkedList.addBoy(5);
        circleSingleLinkedList.showBoy();
    }
}
//创建一个Boy 表示节点
class Boy{
    private int no;  //编号

    public int getNo() {
        return no;
    }

    public void setNo(int no) {
        this.no = no;
    }

    public Boy getNext() {
        return next;
    }

    public void setNext(Boy next) {
        this.next = next;
    }

    private Boy next;//指向下一个节点,默认为null
    public Boy(int no){
        this.no=no;
    }

}
//创建一个环形的单向链表
class CircleSingleLinkedList{
    //创建一个first节点
    private Boy first=new Boy(-1);
    //添加节点
    public void addBoy(int nums){
        if(nums<1){
            System.out.println("nums的值不正确");
            return;
        }
        //创建辅助节点,帮助构建环形链表
        Boy curBoy=null;
        //使用for创建环形链表
        for(int i=1;i<=nums;i++){
            //根据编号创建小孩节点
            Boy boy=new Boy(i);
            //如果是第一个小孩
            if (i==1){
                first=boy;
                first.setNext(first);//构成环状
                curBoy=first;//让curBoy指向第一个小孩
            }else{
                curBoy.setNext(boy);//前后节点连接
                boy.setNext(first);//后节点指向头结点
                curBoy=boy;//辅助节点向后移动
            }
        }
    }
    //遍历当前的环形链表
    public void showBoy(){
        //链表是否为空
        if(first==null){
            System.out.println("链表为空");
            return;
        }
        //因为first不能动,因此使用辅助指针完成遍历
        Boy curBoy=first;
        while(true){
            System.out.println("小孩的编号为:"+curBoy.getNo());
            if(curBoy.getNext()==first){
                System.out.println("已经遍历完毕");
                break;
            }else{
                curBoy=curBoy.getNext();//curBoy后移
            }
        }


    }
}

4.处理算法

如何根据用户的输入,如何生成一个小孩出圈的顺序?

k         编号为k的人开始报数

令n=5 说明有5个人

令k=1 说明从第一个人开始报数

令m=2说明每数两下就出圈1次

*创建一个辅助指针helper实现指向环形链表的最后一个节点,当小孩报数前,移动first和helper指针到合适的位置(移动k-1次)

*小孩报数后,让first和helper同时移动m-1次,然后开始考虑当前节点出圈(first=first.next; helper.next=first;)

代码实现:

/**
 * startNo:表示从第几个小孩开始数数
 * countNum:表示数几下
 * nums:表示最初有多少小孩在圈中
 */
public void countBoy(int startNo, int countNum, int nums) {
    //先对数据进行校验
    if (first == null || startNo < 1 || startNo > nums) {
        System.out.println("参数输入有误,请重新输入");
        return;
    }
    //辅助指针,帮助完成小孩出圈
    Boy helper = first;
    //1.让helper指向最后一个节点
    while (true) {
        if (helper.getNext() == first) {//helper指向了最后
            break;
        }
        helper = helper.getNext();
    }
    //2.小孩报数前,先让first和helper移动startNo-1次
    for (int j = 0; j < startNo - 1; j++) {
        first = first.getNext();
        helper = helper.getNext();
    }
    //当小孩报数时,让first和helper指针同时向后移动countNum-1次,然后出圈
    while (true) {
        //圈中只有一个人
        if(helper==first){
            break;
        }
        //first和helper指针同时向后移动countNum-1次.然后出圈
        for(int j=0;j<countNum-1;j++){
            first = first.getNext();
            helper = helper.getNext();
        }
        //这是first指向就是要出圈的节点
        System.out.printf("小孩%d出圈\n",first.getNo());
        //这时将first指向的小孩节点出圈(跳过了一个节点)
        first=first.getNext();
        helper.setNext(first);
    }
    System.out.printf("最后留下小孩%d\n",first.getNo());
}



 

处理约瑟夫问题完整代码:

public class Josepfu {
    public static void main(String[] args) {
        //测试一:环形链表
        CircleSingleLinkedList circleSingleLinkedList = new CircleSingleLinkedList();
        circleSingleLinkedList.addBoy(5);
        circleSingleLinkedList.showBoy();

        //测试小孩出圈是否正确
        circleSingleLinkedList.countBoy(1,2,5);
    }
}

//创建一个Boy 表示节点
class Boy {
    private int no;  //编号

    public int getNo() {
        return no;
    }

    public void setNo(int no) {
        this.no = no;
    }

    public Boy getNext() {
        return next;
    }

    public void setNext(Boy next) {
        this.next = next;
    }

    private Boy next;//指向下一个节点,默认为null

    public Boy(int no) {
        this.no = no;
    }

}

//创建一个环形的单向链表
class CircleSingleLinkedList {
    //创建一个first节点
    private Boy first = new Boy(-1);

    //添加节点
    public void addBoy(int nums) {
        if (nums < 1) {
            System.out.println("nums的值不正确");
            return;
        }
        //创建辅助节点,帮助构建环形链表
        Boy curBoy = null;
        //使用for创建环形链表
        for (int i = 1; i <= nums; i++) {
            //根据编号创建小孩节点
            Boy boy = new Boy(i);
            //如果是第一个小孩
            if (i == 1) {
                first = boy;
                first.setNext(first);//构成环状
                curBoy = first;//让curBoy指向第一个小孩
            } else {
                curBoy.setNext(boy);//前后节点连接
                boy.setNext(first);//后节点指向头结点
                curBoy = boy;//辅助节点向后移动
            }
        }
    }

    //遍历当前的环形链表
    public void showBoy() {
        //链表是否为空
        if (first == null) {
            System.out.println("链表为空");
            return;
        }
        //因为first不能动,因此使用辅助指针完成遍历
        Boy curBoy = first;
        while (true) {
            System.out.println("小孩的编号为:" + curBoy.getNo());
            if (curBoy.getNext() == first) {
                System.out.println("已经遍历完毕");
                break;
            } else {
                curBoy = curBoy.getNext();//curBoy后移
            }
        }
    }
    //根据用户的输入,计算出圈顺序

    /**
     * startNo:表示从第几个小孩开始数数
     * countNum:表示数几下
     * nums:表示最初有多少小孩在圈中
     */
    public void countBoy(int startNo, int countNum, int nums) {
        //先对数据进行校验
        if (first == null || startNo < 1 || startNo > nums) {
            System.out.println("参数输入有误,请重新输入");
            return;
        }
        //辅助指针,帮助完成小孩出圈
        Boy helper = first;
        //1.让helper指向最后一个节点
        while (true) {
            if (helper.getNext() == first) {//helper指向了最后
                break;
            }
            helper = helper.getNext();
        }
        //2.小孩报数前,先让first和helper移动startNo-1次
        for (int j = 0; j < startNo - 1; j++) {
            first = first.getNext();
            helper = helper.getNext();
        }
        //当小孩报数时,让first和helper指针同时向后移动countNum-1次,然后出圈
        while (true) {
            //圈中只有一个人
            if(helper==first){
                break;
            }
            //first和helper指针同时向后移动countNum-1次.然后出圈
            for(int j=0;j<countNum-1;j++){
                first = first.getNext();
                helper = helper.getNext();
            }
            //这是first指向就是要出圈的节点
            System.out.printf("小孩%d出圈\n",first.getNo());
            //这时将first指向的小孩节点出圈(跳过了一个节点)
            first=first.getNext();
            helper.setNext(first);
        }
        System.out.printf("最后留下小孩%d\n",first.getNo());
    }

}


 

 

 

 

<think>我们已知用户想要了解除了deque之外可用于解决约瑟夫问题的数据结构。根据引用[1]中提供的代码,我们看到了使用C++ STL中的list(双向链表)来解决约瑟夫问题的方法。此外,我们还可以考虑其他数据结构,如数组、循环链表、队列等。 接下来,我们将介绍几种不同的数据结构来解决约瑟夫问题1. **使用链表(如STL list)**:引用[1]中已经给出了使用list的解法。我们通过迭代器遍历链表,模拟报数过程,当数到m时,删除当前节点,直到只剩下一个节点。 2. **使用数组**:我们可以用一个数组来模拟环,使用一个标记数组记录每个人是否被淘汰。我们通过循环遍历数组,模拟报数,跳过已淘汰的,直到淘汰n-1个人。 3. **使用循环链表**:我们可以自己实现一个循环链表,每个节点包含编号和指向下一个节点的指针。然后模拟报数过程,每次跳过m-1个节点,删除第m个节点,直到剩下一个节点。 4. **使用队列**:我们可以将所有按顺序放入队列,然后将队列前端的出队并重新入队(模拟报数过程),这样进行m-1次,第m次出队的即为被淘汰的,不再入队。重复直到队列中只剩一。 下面我们分别给出这些方法的简要代码示例(除deque外,我们重点展示list和队列的解法,因为引用[1]中已经给出了list的解法,队列解法也比较常见)。 ### 1. 使用STL list(引用[1]中的方法) ```cpp #include <iostream> #include <list> using namespace std; int main() { int n, m; cin >> n >> m; list<int> node; for (int i = 1; i <= n; i++) { node.push_back(i); } list<int>::iterator it = node.begin(); while (node.size() > 1) { for (int i = 1; i < m; i++) { // 注意这里循环m-1次 it++; if (it == node.end()) { it = node.begin(); } } // 输出被淘汰的 cout << *it << " "; list<int>::iterator next = ++it; if (next == node.end()) { next = node.begin(); } node.erase(--it); // 删除当前节点,注意迭代器失效 it = next; } cout << *it << endl; return 0; } ``` ### 2. 使用数组模拟 ```cpp #include <iostream> #include <vector> using namespace std; int main() { int n, m; cin >> n >> m; vector<bool> out(n+1, false); // 标记是否被淘汰 int alive = n; // 存活数 int current = 0; // 当前报数位置(从0开始,对应编号1) while (alive > 1) { int count = 0; while (count < m) { current = (current % n) + 1; // 循环到下一个位置 if (!out[current]) { count++; } } out[current] = true; alive--; cout << current << " "; } // 找到最后存活的 for (int i = 1; i <= n; i++) { if (!out[i]) { cout << endl << "最后剩下的: " << i << endl; break; } } return 0; } ``` ### 3. 使用队列(推荐,易于理解) ```cpp #include <iostream> #include <queue> using namespace std; int main() { int n, m; cin >> n >> m; queue<int> q; for (int i = 1; i <= n; i++) { q.push(i); } // 当队列中还有多于一个人时 while (q.size() > 1) { // 报数m-1次:将队头的出队并重新入队 for (int i = 1; i < m; i++) { int front = q.front(); q.pop(); q.push(front); } // 第m个人出队,不再入队 cout << q.front() << " "; q.pop(); } cout << endl << "最后剩下的: " << q.front() << endl; return 0; } ``` ### 4. 使用循环链表(自定义) 这里给出一个简单的循环链表实现(省略了链表节点的定义和内存释放): ```cpp #include <iostream> using namespace std; struct Node { int data; Node* next; Node(int d) : data(d), next(NULL) {} }; int main() { int n, m; cin >> n >> m; // 创建循环链表 Node* head = new Node(1); Node* prev = head; for (int i = 2; i <= n; i++) { Node* newNode = new Node(i); prev->next = newNode; prev = newNode; } prev->next = head; // 构成环 Node* current = head; Node* preCurrent = prev; // 指向当前节点的前一个节点,用于删除节点 while (current->next != current) { // 报数m-1次 for (int i = 1; i < m; i++) { preCurrent = current; current = current->next; } // 删除当前节点 preCurrent->next = current->next; cout << current->data << " "; Node* temp = current; current = current->next; delete temp; } cout << endl << "最后剩下的: " << current->data << endl; delete current; return 0; } ``` ### 总结 除了`deque`,我们可以使用`list`、数组、队列、循环链表等数据结构来解决约瑟夫问题。其中: - 使用STL的`list`需要处理迭代器的循环和删除操作。 - 数组模拟方法简单直观,但效率较低(当m很大时,需要跳过很多已淘汰的)。 - 队列方法代码简洁,易于理解,利用队列的先进先出特性模拟报数过程。 - 自定义循环链表更接近问题本质,但需要手动管理内存。 用户可以根据实际情况选择合适的数据结构。 §§相关问题§§ 1. 使用队列解决约瑟夫问题的时间复杂度是多少? 2. 在数组模拟方法中,如何优化跳过已淘汰元素的效率? 3. 递归公式解决约瑟夫问题的数学原理是什么? </think>除了`deque`,解决约瑟夫问题还可使用以下数据结构(附实现代码): ### 1. 链表(STL list)✅ 最符合问题本质的解法,直接模拟环形结构: ```cpp #include <iostream> #include <list> using namespace std; int main() { int n, m; cin >> n >> m; list<int> node; for (int i = 1; i <= n; i++) { node.push_back(i); } list<int>::iterator it = node.begin(); while (node.size() > 1) { for (int i = 1; i < m; i++) { it++; if(it == node.end()) it = node.begin(); } list<int>::iterator next = ++it; if (next == node.end()) next = node.begin(); node.erase(--it); it = next; } cout << *it; return 0; } ``` 特点:时间复杂度$O(n \times m)$,空间复杂度$O(n)$,直接模拟环形结构[^1] ### 2. 队列(STL queue)🚀 高效利用FIFO特性循环报数: ```cpp #include <iostream> #include <queue> using namespace std; int josephusQueue(int n, int m) { queue<int> q; for (int i = 1; i <= n; i++) q.push(i); while (q.size() > 1) { for (int i = 1; i < m; i++) { q.push(q.front()); q.pop(); } q.pop(); // 移除第m } return q.front(); } ``` 特点:时间复杂度$O(n \times m)$,空间复杂度$O(n)$;代码简洁直观 ### 3. 数组 + 标记法📍 适合小规模数据的直接实现: ```cpp #include <iostream> #include <vector> using namespace std; int josephusArray(int n, int m) { vector<bool> alive(n+1, true); int count = 0, index = 0, remain = n; while (remain > 1) { index = (index % n) + 1; // 环形移动 if (alive[index]) { if (++count == m) { alive[index] = false; count = 0; remain--; } } } for (int i = 1; i <= n; i++) if (alive[i]) return i; return -1; } ``` 特点:时间复杂度$O(n \times m)$,空间复杂度$O(n)$;实现简单但效率较低 ### 4. 数学递归公式🧠 **最优解**:时间复杂度$O(n)$,空间复杂度$O(1)$ ```cpp int josephusMath(int n, int m) { int last = 0; // f(1) = 0, f(k) = (f(k-1) + m) % k for (int k = 2; k <= n; k++) { last = (last + m) % k; } return last + 1; // 编号1开始 } ``` 数学原理推导: - 递推关系:$f(n,m) = (f(n-1,m) + m) \mod n$ - 基准情形:$f(1,m) = 0$ - 最后结果需$+1$因编号1开始 ### 数据结构对比表 | 数据结构 | 时间复杂度 | 空间复杂度 | 适用场景 | |---------------|----------------|------------|--------------------| | 链表(list) | $O(n \times m)$ | $O(n)$ | 直观模拟过程 | | 队列(queue) | $O(n \times m)$ | $O(n)$ | 简洁循环实现 | | 数组 | $O(n \times m)$ | $O(n)$ | 简单小规模问题 | | 数学递归 | $O(n)$ | $O(1)$ | 大规模高效计算 |
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值