POJ 1012 Joseph

 

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

 
    题目大致意思:就是一个约瑟夫问题。
    1.我们已知前面k个人是好人,后面k个人是坏人
    2.坏人一定要死在好人前面,就是说前面k被杀死的人只能是坏人
    3.由于坏人都在后面,所以杀死任何一个坏人,好人的位置都不会有变化
    4.下一个被杀的人的相对位置:

    5.我们只要保证s>=k,那么就不会杀掉好人

    6. 测试数据比较多,如果每输入一个k就算一次m特别耗时间,所以先打表

 

代码如下:

#include <iostream>

using namespace std;

int Joseph(int m,int k)
{
    int left = 2 * k;
    int s = 0;
    for (int i = 0; i < k; i++)
    {
        s = (s + m - 1) % (left - i);
        if (s < k) return 0;
    }
    return 1;
}

int main()
{
    int m, k;
    int a[20];
    for (k = 1; k <= 14; k++)          //题目给定0<k<14
    {
        if (k == 1) a[k] = 2;
        for (int m = 1;; m++)
        {
            if (Joseph(m, k))
            {
                a[k] = m;
                break;
            }
        }
    }
    while (cin >> k)
    {
        cout << a[k] << endl;
    }
}

 

     

 

 

    
posted @ 2017-12-08 09:03  念你成疾  阅读(183)  评论(0编辑  收藏  举报