C++--用list容器处理约瑟夫环问题

约瑟夫环

约瑟夫环问题是一个经典的数学问题,描述如下:

假设有 n 个人站成一圈,编号从 1 到 n。从第一个人开始报数,报到 m 的人出列,然后下一个人继续从 1 开始报数,直到所有人都出列为止。问最后留下的是原来的第几号

用list解


#include <iostream>
#include <list>

using namespace std;

// 模拟约瑟夫环问题,返回最后剩下的节点的编号
int josephus(int n, int m) 
{
    
    //使用一个循环链表
    list<int> people;

    // 初始化人员列表
    for (int i = 1; i <= n; ++i) 
    {
        people.push_back(i);
    }

    //定义当前的迭代器
    auto current = people.begin();//迭代器

	  //当不知道循环的具体次数时,优先使用while循环
    while (people.size() != 1)
    {
        // 移动迭代器,模拟报数过程
        for (int i = 1; i < m; ++i) 
        {
            ++current;//迭代器往前走
            if (current == people.end()) 
            {
                current = people.begin(); // 如果到达末尾,则从头开始
            }
        }

        // 删除当前节点,并移动迭代器到下一个节点
        current = people.erase(current);
        if (current == people.end()) 
        {
            current = people.begin(); // 如果删除的是末尾节点,则将迭代器移到开头
        }
    }

    // 返回最后剩下的节点的编号
    return *(people.begin());
}

int main() 
{
    int n = 5; // 总人数
    int m = 3; // 报数为 3 的人出列

    int survivor = josephus(n, m);
    cout << "最后剩下的人的编号是:" << survivor << endl;

    return 0;
}

在这里插入图片描述

相关推荐

  1. 问题

    2024-04-14 19:12:05       35 阅读
  2. 问题解决

    2024-04-14 19:12:05       37 阅读
  3. Python 问题

    2024-04-14 19:12:05       12 阅读
  4. C#实现算法

    2024-04-14 19:12:05       25 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-04-14 19:12:05       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-04-14 19:12:05       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-04-14 19:12:05       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-04-14 19:12:05       20 阅读

热门阅读

  1. 【接着模拟赛】2024.4.14

    2024-04-14 19:12:05       17 阅读
  2. 239. 滑动窗口最大值

    2024-04-14 19:12:05       14 阅读
  3. win10清华源按装OPENCV和其他软件

    2024-04-14 19:12:05       15 阅读
  4. Csharp_pta2

    2024-04-14 19:12:05       14 阅读
  5. 中文域名有必要注册吗?

    2024-04-14 19:12:05       14 阅读
  6. conda搭建与管理python环境

    2024-04-14 19:12:05       14 阅读
  7. 为什么我们应该切换到Rust

    2024-04-14 19:12:05       13 阅读
  8. 源码安装 clr - hip runtime

    2024-04-14 19:12:05       12 阅读
  9. 【C++】vector的模拟实现

    2024-04-14 19:12:05       17 阅读
  10. AI技术创业有哪些机会?

    2024-04-14 19:12:05       15 阅读