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.
大意就是:給出k個好孩子和k個壞孩子,好孩子在前,壞孩子在后。然后圍成一圈,從第一個開始報數,報到m的退出,求最小的的m滿足前k個出局的孩子都是壞孩子。
對于約瑟夫環問題大家的第一影響應該是模擬,數組和鏈表都行,但是這里如果用不加優化的模擬的話,超時是不可避免的,對于k=13,m是200多萬,一個一個枚舉,會死人的。。。不過用數組模擬時有個優化,就是m對剩下的人數先取模,也就是說剩下的人數的整數倍對最后的結果不影響。這里可以剪掉很多。還有就是得先把這13個結果算出來,不然還是會超時,因為case居多。。。
下面給出官方的代碼(建議先自己想)

官方
1
/**//*
2
k個好孩子編號從k個壞孩子按順序圍成一個圈,請求出一個最小的m使得按照約瑟夫的規則
3
即從當前號開始數數(當前號為1),數到m的人退出,其他人重新重新按順序圍成一個圈,從退出的人之后一個人繼續進行下一輪。
4
這題要求一個最小的m使得在第一個好孩子出隊之前所有的壞孩子都已經出隊,也就是所有的壞孩子都要先出隊。
5
6
顯然最直接的方法就是從小到大枚舉m的值然后去判定是否滿足要求。
7
在對確定的m進行判定的時候只需模擬規則即可,復雜度為m*O(模擬)
8
因為m比較大所以如果用鏈表復雜度將會比較大,如果用數組,每次數m下只需取模即可,所以模擬的復雜度會是2*k*k,整個復雜度是O(m*k*k)
9
當然由于k最大只有13,一旦發現自己代碼超時就應該感覺到,題目可能有重復數據,也就是說可以一次性先算出來,然后O(1)訪問,甚至可以本地全部算出來然后打表。
10
11
*/
12
//Joseph
13
#include <iostream>
14
using namespace std;
15
const int MAXN = 30;
16
int n, m, k;
17
int man[MAXN], ans[MAXN];
18
19
bool ok()
{
20
int i, j;
21
for(i = 0; i < n; ++i) man[i] = i;//可以編號k個好孩子為0~k-1,k個壞孩子編號為k~2*k-1
22
23
int p = (m-1+n)%n;
24
i = 0;
25
while(man[p] >= k)
{
26
// printf("%d ", man[p]);
27
++i;
28
for(j = p; j < n-1; ++j)//將后面的人往前移動一步
29
man[j] = man[j+1];
30
--n;
31
p = (p+m-1)%n;//當前已經走了一步,再走m-1
32
}
33
34
return i == k;
35
}
36
37
int main()
{
38
for(k = 1; k < 14; ++k)
{
39
for(m = 1; ; ++m)
{
40
n = k*2;
41
if(ok())
{
42
ans[k] = m;
43
break;
44
}
45
}
46
}
47
while(scanf("%d", &k), k) printf("%d\n", ans[k]);
48
return 0;
49
}
50