# POJ 1012 Joseph C++版

POJ题解 3356浏览

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

Slyar:约瑟夫问题都知道了，这个题就是给出一个k，总人数n等于2k，让你找到一个报数m，使得后k个人先出列…

```#include
#include

using namespace std;

int work(int, int);

int main()
{
int i, k;
vector array(14);

for (k = 1; k < 14; k++)
{
for (i = k + 1; ;i += (k + 1))
{
if (work(k, i))
{
array[k] = i;
break;
}
else if (work(k, i + 1))
{
array[k] = i + 1;
break;
}
}
}

while (1)
{
cin >> k;
if (k == 0) break;
cout << array[k] << endl;
}

return 0;
}

int work(int k, int m)
{
int i = 0, len = 2 * k;

while (len > k)
{
i = (i + m - 1) % len;
if (i < k) return 0;
len--;
}

return 1;
}
```

### 网友最新评论 (4)

1. chx : 我也想知道啊……
我也是 我想知道
匿名11年前 (2011-04-05)回复
2. 我也想知道啊……
chx12年前 (2010-07-08)回复
3. @Yuan 哪有m+=k+1？貌似只有i += (k + 1)...i++为什么不行？因为不是每次都报1啊...
Slyar12年前 (2009-11-12)回复
4. 请问一下这里为什么 m+=k+1呢？ m++为什么不行？
Yuan12年前 (2009-11-12)回复