当前位置: 首页 > news >正文

18063 圈中的游戏

### 思路

这个问题是经典的约瑟夫环问题。我们可以使用链表来模拟这个过程。具体步骤如下:
1. 创建一个循环链表,表示所有人。
2. 从第一个人开始,依次报数。
3. 每报到3的人退出圈子,直到只剩下一个人。

### 伪代码

```
function josephus(n):
    create a circular linked list with n nodes
    current = head of the list

    while more than one node in the list:
        move current to the next node twice (to skip two nodes)
        remove the node after current (the third node)

    return the value of the remaining node
```

### C++代码

#include <iostream>
using namespace std;struct Node {int data;Node* next;Node(int val) : data(val), next(nullptr) {}
};int findLastPerson(int n) {// 创建循环链表Node* head = new Node(1);Node* prev = head;for (int i = 2; i <= n; ++i) {prev->next = new Node(i);prev = prev->next;}prev->next = head; // 形成循环链表// 初始化指针Node* current = head;while (current->next != current) {// 移动两次for (int i = 0; i < 2; ++i) {current = current->next;}// 删除当前节点Node* temp = current->next;current->data = temp->data;current->next = temp->next;delete temp;}int lastPerson = current->data;delete current;return lastPerson;
}int main() {int n;cin >> n;cout << findLastPerson(n) << endl;return 0;
}

### 总结

通过使用循环链表,我们可以有效地模拟报数和删除操作。每次报数到3时,删除相应的节点,直到只剩下一个节点。这个方法的时间复杂度是O(n),适合处理较大的输入规模。


http://www.mrgr.cn/news/48501.html

相关文章:

  • 探索极简计算的新边界:从Uxn虚拟机看未来编程生态
  • 儿童画画在线支付预约报名表单在线制作小程序源码系统 带完整的安装代码包以及搭建部署教程
  • 思迅商云8四级分类
  • 哪个牌子的护眼灯防蓝光效果好?五款市场上评价较高的护眼台灯
  • xtu oj 彩球
  • 自监督学习:引领机器学习的新革命
  • Java Mail腾讯企业邮箱或其他邮箱发送邮件失败bug记录
  • MySQL的基础语法-2
  • 电商新动力:SpringBoot购物推荐网站开发详解
  • 国内首个专业领域知识增强服务框架 KAG 技术报告,助力大模型落地垂直领域
  • Apple提出MM1.5:多模态大型语言模型微调的方法、分析和见解
  • Ubuntu卸载Mysql【ubuntu 24.04/mysql 8.0.39】
  • 利用Spring Boot构建医疗病历B2B平台的优势
  • yolo5快速上手训练数据集
  • 125页满分PPT | 数据架构革新顶层规划方案
  • 弧光保护装置的应用
  • 大模型完美攻略手册(从入门到专家)精选资源集,新手入门教程!
  • 在python中如何判断回文串(二)?
  • 漏洞挖掘和渗透测试的区别是什么?(非常详细),零基础入门到精通,看这一篇就够了
  • 【华为】RIP与 BFD联动