博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
PKU 1012
阅读量:4676 次
发布时间:2019-06-09

本文共 1924 字,大约阅读时间需要 6 分钟。

Joseph
Time Limit: 1000MS
Memory Limit: 10000K
Total Submissions: 26955
Accepted: 10073

Description

The Joseph's problem is notoriously known. For those who are not familiar with the original problem: from among n people, numbered 1, 2, . . ., n, standing in circle every mth is going to be executed and only the life of the last remaining person will be saved. Joseph was smart enough to choose the position of the last remaining person, thus saving his life to give us the message about the incident. For example when n = 6 and m = 5 then the people will be executed in the order 5, 4, 6, 2, 3 and 1 will be saved.
Suppose that there are k good guys and k bad guys. In the circle the first k are good guys and the last k bad guys. You have to determine such minimal m that all the bad guys will be executed before the first good guy.

Input

The input file consists of separate lines containing k. The last line in the input file contains 0. You can suppose that 0 < k < 14.

Output

The output file will consist of separate lines containing m corresponding to k in the input file.

Sample Input

3 4 0

Sample Output

5 30

Source

模拟算法肯定能写出来,不过昨天研究了一下约瑟夫的数学解法,发现了一个公式,写出来吧:

 

1 
int
 josefus(
int
 n,
int
 m) 
//
n是总人数;m是报的数;返回最后生存的鸟人
2 
{
3 
    
int
 i, s
=
0
;
4 
    
for
 (i
=
2
; i
<=
n; i
++
)
5 
    s
=
(s
+
m)
%
i;
6 
    
return
 (s
+
1
);
7 
}

大牛的解法:

ExpandedBlockStart.gif
代码
 1 
#include
<
iostream
>
 2 
using
 
namespace
 std;
 3 
 4 
 5 
int
 main()
 6 
{
 7 
int
 k
=
0
;
 8 
int
 a[
14
=
 {
0
};
 9 
while
( (cin
>>
k)
&&
(k
!=
0
) )
10 
{
11 
if
(a[k])
12 
{
13 
cout
<<
a[k]
<<
endl;
14 
continue
;
15 
}
16 
17 
for
(
int
 m
=
k
+
1
;;m
++
)
18 
{
19 
int
 n
=
2
*
k,i
=
0
,flag
=
0
;
20 
while
(
1
)
21 
{
22 
i
=
(i
+
m
-
1
)
%
n;
23 
if
(i
>=
0
&&
i
<
k) 
break
;
24 
else
 flag
++
;
25 
n
--
;}
26 
27 
if
(flag
==
k)
28 
{
29 
a[flag] 
=
 m;
30 
cout
<<
m
<<
endl;
31 
break
;
32 
}
33 
}
34 
35 
}
36 
37 
return
 
0
;
38 
}

这兄弟给了讲解,貌似这一题用了十分取巧的方法:

 

转载于:https://www.cnblogs.com/woodywu/archive/2010/02/10/1667348.html

你可能感兴趣的文章
hall wrong behavior
查看>>
Markdown test
查看>>
Collection集合
查看>>
int最大值+1为什么是-2147483648最小值-1为什么是2147483647
查看>>
【C++】const在不同位置修饰指针变量
查看>>
github新项目挂历模式
查看>>
编写jquery插件
查看>>
敏捷开发笔记
查看>>
神秘海域:顶级工作室“顽皮狗”成长史(下)
查看>>
C++指针、引用知多少?
查看>>
services 系统服务的启动、停止、卸载
查看>>
Fiddler 网页采集抓包利器__手机app抓包
查看>>
Number and String
查看>>
java中的值传递和引用传递2<原文:http://blog.csdn.net/niuniu20008/article/details/2953785>...
查看>>
css实现背景图片模糊
查看>>
什么是runtime?什么是webgl?
查看>>
秋季学习总结
查看>>
categorical_crossentropy VS. sparse_categorical_crossentropy
查看>>
强引用,弱引用,4种Java引用浅解(涉及jvm垃圾回收)
查看>>
多线程如何确定线程数
查看>>