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個(gè)好孩子和k個(gè)壞孩子,好孩子在前,壞孩子在后。然后圍成一圈,從第一個(gè)開(kāi)始報(bào)數(shù),報(bào)到m的退出,求最小的的m滿足前k個(gè)出局的孩子都是壞孩子。
對(duì)于約瑟夫環(huán)問(wèn)題大家的第一影響應(yīng)該是模擬,數(shù)組和鏈表都行,但是這里如果用不加優(yōu)化的模擬的話,超時(shí)是不可避免的,對(duì)于k=13,m是200多萬(wàn),一個(gè)一個(gè)枚舉,會(huì)死人的。。。不過(guò)用數(shù)組模擬時(shí)有個(gè)優(yōu)化,就是m對(duì)剩下的人數(shù)先取模,也就是說(shuō)剩下的人數(shù)的整數(shù)倍對(duì)最后的結(jié)果不影響。這里可以剪掉很多。還有就是得先把這13個(gè)結(jié)果算出來(lái),不然還是會(huì)超時(shí),因?yàn)閏ase居多。。。
下面給出官方的代碼(建議先自己想)

官方
1
/**//*
2
k個(gè)好孩子編號(hào)從k個(gè)壞孩子按順序圍成一個(gè)圈,請(qǐng)求出一個(gè)最小的m使得按照約瑟夫的規(guī)則
3
即從當(dāng)前號(hào)開(kāi)始數(shù)數(shù)(當(dāng)前號(hào)為1),數(shù)到m的人退出,其他人重新重新按順序圍成一個(gè)圈,從退出的人之后一個(gè)人繼續(xù)進(jìn)行下一輪。
4
這題要求一個(gè)最小的m使得在第一個(gè)好孩子出隊(duì)之前所有的壞孩子都已經(jīng)出隊(duì),也就是所有的壞孩子都要先出隊(duì)。
5
6
顯然最直接的方法就是從小到大枚舉m的值然后去判定是否滿足要求。
7
在對(duì)確定的m進(jìn)行判定的時(shí)候只需模擬規(guī)則即可,復(fù)雜度為m*O(模擬)
8
因?yàn)閙比較大所以如果用鏈表復(fù)雜度將會(huì)比較大,如果用數(shù)組,每次數(shù)m下只需取模即可,所以模擬的復(fù)雜度會(huì)是2*k*k,整個(gè)復(fù)雜度是O(m*k*k)
9
當(dāng)然由于k最大只有13,一旦發(fā)現(xiàn)自己代碼超時(shí)就應(yīng)該感覺(jué)到,題目可能有重復(fù)數(shù)據(jù),也就是說(shuō)可以一次性先算出來(lái),然后O(1)訪問(wèn),甚至可以本地全部算出來(lái)然后打表。
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;//可以編號(hào)k個(gè)好孩子為0~k-1,k個(gè)壞孩子編號(hào)為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)//將后面的人往前移動(dòng)一步
29
man[j] = man[j+1];
30
--n;
31
p = (p+m-1)%n;//當(dāng)前已經(jīng)走了一步,再走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