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
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.
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 0Sample Output
5 30
约瑟夫环问题的改版。题意:输入k,前k个为good boy,后k个为bad boy,输出最小m使得在第一个good boy 被淘汰前 bad boy都被淘汰。网上有约瑟夫环递推公式:f(n)=(f(n-1)+m-1)/i i>1.
k=3,m=5;f(0)=0; f(1)=(f(0)+5-1)%6=4,f(2)=(f(1)+5-1)%5=4,前k个退出的人必为后k个人。只要前k轮有f(n)<k,则m不符合题意.还有打表法存答案直接输出不用算。
#include<iostream> using namespace std; int main() { int a[14]; int i,j,k,temp; for(k=1;k<14;k++)//k为输入的人数 { for(i=k+1;;i++)//计算最小m { temp=0; for(j=0;j<k;j++) { temp=(temp+i-1)%(2*k-j); if(temp<k) { break; } } if(j==k) { a[k]=i; break; } } } while(cin>>k) { if(k==0) { break; } cout<<a[k]<<endl; } }