剑指Offer 面试题45:圆圈中最后剩下的数字(约瑟夫环问题)

原书题目:0, 1, … , n-1 这n个数字排成一个圈圈,从数字0开始每次从圆圏里删除第m个数字。求出这个圈圈里剩下的最后一个数字。

牛客网改编:孩子们的游戏(圆圈中最后剩下的数)

参与人数:1699  时间限制:1秒 空间限制:32768K

本题知识点: 模拟


题目描述
每年六一儿童节,NowCoder都会准备一些小礼物去看望孤儿院的小朋友,今年亦是如此。HF作为NowCoder的资深元老,自然也准备了一些小游戏。其中,有个游戏是这样的:首先,让小朋友们围成一个大圈。然后,他随机指定一个数m,让编号为0的小朋友开始报数。每次喊到m的那个小朋友要出列唱首歌,然后可以在礼品箱中任意的挑选礼物,并且不再回到圈中,从他的下一个小朋友开始,继续0...m-1报数....这样下去....直到剩下最后一个小朋友,可以不用表演,并且拿到NowCoder名贵的“名侦探柯南”典藏版(名额有限哦!!^_^)。请你试着想下,哪个小朋友会得到这份礼品呢?


方法1: 用环形单链表来模拟圆圈
可转换为带环单链表删除结点的问题:创建一个总共有n个结点的环形链表,然后每次在这个链表中删除第m个结点。

时间复杂度为O(n*m),空间复杂度为O(n).

方法2:映射,找规律
时间复杂度为O(n),空间复杂度为O(1).
此题只需求最后一个报数胜利者,我们可以用数学归纳法解决该问题,为了讨论方便,先把问题稍微改变一下,并不影响原意:

问题描述:n个人(编号0~(n-1)),从0开始报数,报到(m-1)的退出,剩下的人继续从0开始报数。求胜利者的编号。

分析:

我们知道第一个人(编号一定是m%n-1) 出列之后,剩下的n-1个人组成了一个新的约瑟夫环(以编号为k=m%n的人开始):
        k  k+1  k+2  ... n-2, n-1, 0, 1, 2, ... k-2并且从k开始报0。
现在我们把他们的编号做一下转换:
k       --> 0
k+1   --> 1
k+2   --> 2
...
k-2   --> n-2
k-1   --> n-1
变换后就完完全全成为了(n-1)个人报数的子问题,假如我们知道这个子问题的解: 例如x是最终的胜利者,那么根据上面这个表把这个x变回去不刚好就是n个人情况的解吗?!!变回去的公式很简单,不难推导出:x'=(x+k)%n。
令f[i]表示i个人玩游戏报m退出最后胜利者的编号,最后的结果自然是f[n]。

相应的递推关系为:

f(1)=0;
f(n)=(f(n-1)+m)%n;  (n>1, n∈N)
有了这个公式,我们要做的就是从1-n顺序算出f(i)的数值,最后结果是f(n)。 因为实际生活中编号总是从1开始,我们输出f(n)+1。

注意:此题中m是不变的量,从刚开始输入后就一直不变,而n逐一减小...

方法2

递归实现 AC代码:

class Solution {
public:
int LastRemaining_Solution(int n, int m)
{
if(n<1 || m<1) return -1;
if(n==1) return 0;
return (LastRemaining_Solution(n-1,m)+m)%n;
}
};

class Solution {
public:
int LastRemaining_Solution(unsigned int n, unsigned int m)
{
if(n==0 || m==0) return -1;
if(n==1) return 0;
return (LastRemaining_Solution(n-1,m)+m)%n;
}
};

方法2
迭代实现 AC代码:

class Solution {
public:
int LastRemaining_Solution(unsigned int n, unsigned int m)
{
if(n==0 || m==0) return -1;
if(n==1) return 0;
int last=0; // f(1,x)=0 for(unsigned int i=2; i<=n; i++)
{
last=(last+m)%i;
}
return last;
}
};

需要注意的是:newcoder OJ上给的编号是从0开始的,而不是从1开始的,输入不合法时要求返回-1 .

ZOJ上也有相关的题:

ZOJ Problem Set - 1088

提交网址: http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=88

Time Limit: 10 Seconds      Memory Limit: 32768 KB

Recently you must have experienced that when too many people use the BBS simultaneously, the net becomes very, very slow.
To put an end to this problem, the Sysop has developed a contingency scheme for times of peak load to cut off net access for some buildings of the university in a systematic, totally fair manner. Our university buildings were enumerated randomly from 1 to n. XWB is number 1, CaoGuangBiao (CGB) Building is number 2, and so on in a purely random order.
Then a number m would be picked at random, and BBS access would first be cut off in building 1 (clearly the fairest starting point) and then in every mth building after that, wrapping around to 1 after n, and ignoring buildings already cut off. For example, if n=17 and m=5, net access would be cut off to the buildings in the order [1,6,11,16,5,12,2,9,17,10,4,15,14,3,8,13,7]. The problem is that it is clearly fairest to cut off CGB Building last (after all, this is where the best programmers come from), so for a given n, the random number m needs to be carefully chosen so that building 2 is the last building selected.

Your job is to write a program that will read in a number of buildings n and then determine the smallest integer m that will ensure that our CGB Building can surf the net while the rest of the university is cut off.

Input Specification

The input file will contain one or more lines, each line containing one integer n with 3 <= n < 150, representing the number of buildings in the university.
Input is terminated by a value of zero (0) for n.

Output Specification

For each line of the input, print one line containing the integer m fulfilling the requirement specified above.

Sample Input

3
4
5
6
7
8
9
10
11
12
0

Sample Output

2
5
2
4
3
11
2
3
8
16

AC代码(PHP实现):

<?php
function judge($m, $n)
{
$from = 0;
for($i = 2; $i < $n; $i++)
$from = ($from + $m)%($i);
if($from + 1 == 1) return 1;
else return 0;
}
$fd = STDIN; // STDIN是oj提供的常量,等价于 fopen("php://stdin","r"));
while(fscanf($fd, "%d", $n)==1 && $n!=0)
{
$m = 1;
while(!judge($m, $n))
{
++$m;
}
echo $m."\n";
}

带测试的PHP代码,请参考本人博文:详解OJ(Online Judge)中PHP代码的提交方法及要点【举例:ZOJ 1001 (A + B Problem)】 的末尾部分...

相关链接:

http://www.cnblogs.com/AndyJee/p/4687715.html

C++版 - 剑指Offer 面试题45:圆圈中最后剩下的数字(约瑟夫环问题,ZOJ 1088:System Overload类似)题解的更多相关文章

  1. Leetcode_面试题62. 圆圈中最后剩下的数字(约瑟夫环)

    经典的约瑟夫环,n个人排成一圈,第m个出队. 递归 code1 class Solution { public: int f(int n,int m){ if(n==1){ //递归边界,最后一个 r ...

  2. 【剑指Offer】孩子们的游戏(圆圈中最后剩下的数) 解题报告(Python)

    [剑指Offer]孩子们的游戏(圆圈中最后剩下的数) 解题报告(Python) 标签(空格分隔): 剑指Offer 题目地址:https://www.nowcoder.com/ta/coding-in ...

  3. 剑指 Offer 62. 圆圈中最后剩下的数字 + 约瑟夫环问题

    剑指 Offer 62. 圆圈中最后剩下的数字 Offer_62 题目描述 方法一:使用链表模拟 这种方法是暴力方法,时间复杂度为O(nm),在本题中数据量过大会超时. 方法二:递归方法 packag ...

  4. 【剑指Offer】46、圆圈中最后剩下的数

      题目描述:   每年六一儿童节,牛客都会准备一些小礼物去看望孤儿院的小朋友,今年亦是如此.HF作为牛客的资深元老,自然也准备了一些小游戏.其中,有个游戏是这样的:首先,让小朋友们围成一个大圈.然后 ...

  5. 【剑指offer】孩子们的游戏(圆圈中最后剩下的数)

    题目描述 每年六一儿童节,牛客都会准备一些小礼物去看望孤儿院的小朋友,今年亦是如此.HF作为牛客的资深元老,自然也准备了一些小游戏.其中,有个游戏是这样的:首先,让小朋友们围成一个大圈.然后,他随机指 ...

  6. 《剑指offer》面试题45 圆圈中最后剩下的数字(Java版本)

    引言 这道题网上的讲解都是直接抄书,没意思,所以想自己写一写,补充一下,便于自己理解.另外,大家都忽略了经典解法,虽然这种解法效率不及第二种,但是我觉得在项目当中阅读性其实很重要,牺牲一点点效率保证代 ...

  7. 剑指Offer 46. 孩子们的游戏(圆圈中最后剩下的数) (其他)

    题目描述 每年六一儿童节,牛客都会准备一些小礼物去看望孤儿院的小朋友,今年亦是如此.HF作为牛客的资深元老,自然也准备了一些小游戏.其中,有个游戏是这样的:首先,让小朋友们围成一个大圈.然后,他随机指 ...

  8. [剑指offer] 46. 孩子们的游戏(圆圈中最后剩下的数)

    题目描述 随机指定一个数m,让编号为0的小朋友开始报数.每次喊到m-1的那个小朋友要出列,并且不再回到圈中,从他的下一个小朋友开始,继续0...m-1报数....这样下去....直到剩下最后一个小朋友 ...

  9. 剑指offer-面试题62-圆圈中最后剩下的数字-约瑟夫环-解法2

    /* 题目: 约瑟夫环问题. 思路: 数学规律 f(n)=0(n=1),[f(n-1,m)+m]%n(n>1) */ #include<iostream> #include<l ...

随机推荐

  1. 【SerpentAI:Python开源游戏智能体开发框架——相比OpenAI Universe可导入自己的游戏、可脱离Docker/VNC运行】

    https://weibo.com/fly51fly?from=myfollow_all&is_all=1#1514439335614 [SerpentAI:Python开源游戏智能体开发框架 ...

  2. 检索html页自生成&nasp;标签,并替换为空(即去掉空格)

    在开发过程中,遇到这样的一种情况,就是页面有时候不知道什么原因会自动生成一些元素,从而打乱自己原有的一些布局. 原html页源代码: 生成后的html源代码: 可以明显看出自动生成了很多   元素,现 ...

  3. MongoDB + Express 环境搭建记

    最近项目需要使用 MongoDB,所以不得不搭建 MongoDB 环境,此文记录搭建过程及使用过程中需要了解的问题. Linux + Windows 混合搭建调试 MongoDB 记录 版本介绍 : ...

  4. angular 实现 echarts 拖动区域进行放大 方法

    实现逻辑: 1.通过鼠标摁下事件  和弹出事件  获取x轴的index  之后去x轴的list中去获取两个坐标点 2.之后将这两个数据作为参数  传到后台更新数据 3.记录下来这两个坐标点 放到lis ...

  5. spo0lsv病毒分析

    1.样本概况 1.1 样本信息 病毒名称:spo0lsv.exe 所属家族:Worm MD5值:512301C535C88255C9A252FDF70B7A03 SHA1值:CA3A1070CFF31 ...

  6. MySQL中 DECIMAL FLOAT DOUBLE的区别

    第一篇文章: MySQL中Decimal类型和Float Double等区别 MySQL中存在float,double等非标准数据类型,也有decimal这种标准数据类型. 其区别在于,float,d ...

  7. 对excel文件的读取

    poi上传文件,准备 <dependencies><dependency> <groupId>org.apache.poi</groupId> < ...

  8. redis_字符串对象

    Redis总共支持五种数据类型:string,hash,list,set及zset.这里介绍字符串类型的实现 首先了解字符串对象的结构 // redis对象内存分配,列出主要相关的属性 redisOb ...

  9. influence maximization

    Robust Influence Maximization 首先简要介绍一下这个问题:在一个社交网络图中寻找固定数量的节点,使得这些节点对所有节点的影响值尽可能的大.这个问题由于在病毒式营销,谣言监控 ...

  10. mysql-exporter

    [1] https://blog.frognew.com/2017/08/use-prometheus-monitoring-mysql.html [2] http://www.ywnds.com/? ...