洛谷 P1996 约瑟夫问题 题解 循环链表

约瑟夫问题

题目描述

n n n 个人围成一圈,从第一个人开始报数,数到 m m m 的人出列,再由下一个人重新从 1 1 1 开始报数,数到 m m m 的人再出圈,依次类推,直到所有的人都出圈,请输出依次出圈人的编号。

输入格式

输入两个整数 n , m n,m n,m。

输出格式

输出一行 n n n 个整数,按顺序输出每个出圈人的编号。

样例 #1

样例输入 #1

复制代码
10 3

样例输出 #1

复制代码
3 6 9 2 7 1 8 5 10 4

提示

1 ≤ m , n ≤ 100 1 \le m, n \le 100 1≤m,n≤100

原题

洛谷P1996------传送门

代码

cpp 复制代码
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int main()
{
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    int n, m;
    cin >> n >> m;
    list<int> lt; // 循环链表
    for (int i = 1; i <= n; i++)
    {
        lt.push_back(i); // 将n个人的序号插入链表
    }
    auto index = lt.begin(); // 链表头节点的指针
    while (!lt.empty())      // 所有人全部出圈则循环终止
    {
        for (int i = 1; i < m; i++) // 由于n和m很小,所以可以模拟报数过程
        {
            index++;
            if (index == lt.end())
                index = lt.begin();
        }
        cout << *index << ' ';   // 输出出圈人编号
        index = lt.erase(index); // 删除出圈人所在节点,并更新指针指向删除的位置
        if (index == lt.end())
            index = lt.begin();
    }
    return 0;
}
相关推荐
浮灯Foden40 分钟前
算法-每日一题(DAY13)两数之和
开发语言·数据结构·c++·算法·leetcode·面试·散列表
淡海水1 小时前
【原理】Struct 和 Class 辨析
开发语言·c++·c#·struct·class
西工程小巴1 小时前
实践笔记-VSCode与IDE同步问题解决指南;程序总是进入中断服务程序。
c语言·算法·嵌入式
Tina学编程2 小时前
48Days-Day19 | ISBN号,kotori和迷宫,矩阵最长递增路径
java·算法
Moonbit2 小时前
MoonBit Perals Vol.06: MoonBit 与 LLVM 共舞 (上):编译前端实现
后端·算法·编程语言
青草地溪水旁2 小时前
UML函数原型中stereotype的含义,有啥用?
c++·uml
青草地溪水旁2 小时前
UML函数原型中guard的含义,有啥用?
c++·uml
百度Geek说3 小时前
第一!百度智能云领跑视觉大模型赛道
算法
big_eleven3 小时前
轻松掌握数据结构:二叉树
后端·算法·面试
big_eleven3 小时前
轻松掌握数据结构:二叉查找树
后端·算法·面试