POJ-1012 Joseph-约瑟夫问题好人坏人

来源:互联网 发布:盘古网络河北肉牛 编辑:程序博客网 时间:2024/04/30 22:54
Joseph
Time Limit: 1000MS Memory Limit: 10000KTotal Submissions: 50354 Accepted: 19143

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

340

Sample Output

530

Source

Central Europe 1995

#include <iostream>#include <cstring>#include <cstdio>using namespace std;int main(){    int k,i,j,m,n,r[15],a[30];    memset(r,0,sizeof(r));    for(i=1; i<14; ++i)//人数范围是1-14    {        memset(a,0,sizeof(a));        n=2*i;        m=1;//先m=1开始尝试        for(j=1; j<=i; j++)        {   /*运用公式j=(j+m-1)%(n-i)            (这个公式求出的只是在新的排列下出现的位置),            推导出下一个出现的元素在第几号位置,*/            a[j]=(a[j-1]+m-1)%(n-j+1);            if(a[j]<i)//1-k是好人,不能杀            {                j=0;                ++m;//穷举m一次次尝试            }        }        r[i]=m;    }    while(cin>>k,k)        cout<<r[k]<<endl;    return 0;}


0 0