约瑟夫环问题就是n个人围成一圈,然后循环报数,每次喊道k的人出列;
递归实现:
例:10个人,0~9号围成一圈,k为3;
递归的数据为,m个人,说k的出列当前在第几个人,
int
fun(
int
m,
int
k,
int
I)
{
if
(i==1)
return
(m+k-1)%m;//意思是说这个是起点为零开始的转k次,第k个人出列
else
return
(fun(m-1,k,i-1)+k)%m;//意思是说递归下一层出列的人的位置,当作这次报数的起点,来报数,报k的人再出列,依次递归向下进行;
}
例题:
|
|
|
Problem 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
|
Sample Input
3 4 0 |
Sample Output
5 30
解题思路:我的思路是暴力打表^0^,从1开始暴力,每次出列一个人判断是否是好人,如果在坏人没枪毙完之前就杀死一个好人,这个x就被弃掉,一直暴力下去;
感悟:每天学一点新东西
代码:
#include
using namespace std; int main() { } 打表
约瑟夫环问题
#include #define N 28 using namespace std; int k,visit[N]; int fun(int m,int k,int i)//约瑟夫环 //m个人,说k的人出列,第i个出列的 { } int Joseph(int k)//寻找那个最小的 { } int main() { } |