天天看點

PKU 1012

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

Central Europe 1995

模拟算法肯定能寫出來,不過昨天研究了一下約瑟夫的數學解法,發現了一個公式,寫出來吧:

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 }

大牛的解法:

代碼

 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 }

這兄弟給了講解,貌似這一題用了十分取巧的方法:

 http://cid-6d7e68dedf9fc44e.spaces.live.com/blog/cns!6D7E68DEDF9FC44E!130.entry