Josephus约瑟环问题
来源:互联网 发布:java 服务器监控 编辑:程序博客网 时间:2024/06/05 19:40
约瑟环问题描述:n个人有序围成一圈报数,报到M的就退(自)出(杀),再从头开始报数,由此循环,求剩下最后一人的序号。
第一种直觉的想法是弄个list循环:
int Josephus(unsigned int n, unsigned int m){ // invalid input if(n < 1 || m < 1) return -1;
// initiate a list with n integers (1, 2, ... n ) list<int> integers; for(int i = 1; i < =n; ++ i) integers.push_back(i); list<int>::iterator curinteger = integers.begin(); while(integers.size() > 1) { // find the mth integer. Note that std::list is not a circle // so we should handle it manually for(unsigned int i = 1; i < m; ++ i) { curinteger ++; if(curinteger == integers.end()) curinteger = integers.begin(); } // remove the mth integer. Note that std::list is not a circle // so we should handle it manually list<int>::iterator nextinteger = ++ curinteger; if(nextinteger == integers.end()) nextinteger = integers.begin(); -- curinteger; integers.erase(curinteger); curinteger = nextinteger; } return *(curinteger);}
我按照网上的说法去找了《具体数学》第一章里的约瑟环问题,书中是利用递归,想法不错,不过算起来应该很麻烦。
把这n个人想象成站成一列,报数,n/m个人自杀了,还剩n-n/m个人,关键是最后一个自杀的人后边的n%m个会影响下一轮的报数,然后下一个队列开始时只剩了n-n/m个人了。所以要使用两个计数器,一个count记录报数,一个suicide记录自杀的人在现有队列里的位置。我写了一段,但是没有轮子哥的代码简洁。
下面是整(和)理(谐)过的轮子哥的代码,
int Josephus(int n, int m){ vector<int> people; for (int i = 1; i <= n; i++) { people.push_back(i); } int suicide = 0; int count = 1; while (people.size() > 1) { if (count == m) { people.erase(people.begin() + suicide); suicide--; } count = count % m + 1; suicide
= (suicide
+ 1) % people.size(); } return people[0];}
0 0
- Josephus约瑟环问题
- Josephus问题
- Josephus问题
- Josephus问题
- Josephus问题
- josephus 问题
- Josephus问题
- Josephus问题
- josephus问题
- Josephus问题
- Josephus问题
- Josephus问题
- Josephus问题
- Josephus问题
- Josephus问题
- Josephus问题
- Josephus问题
- Josephus问题
- hdu1541 Stars 树状数组水题
- 输出一个数字各个位数和
- 常见HTTP状态(304,503)
- Python学习笔记 函数
- 解决 越狱后ios 密码丢失的问题
- Josephus约瑟环问题
- IOI2014题解
- 单链表多成员的插入、删除、查找、打印
- 下面三个导航栏Item有什么区别啊???
- 快速部署安装rrdtool
- CentOS 7上安装翻译软件
- 黑马程序员-OC-自定义构造方法和description方法
- iOS开发网络篇—JSON介绍
- 我的数值计算第一天。