1. 程式人生 > >poj 1012 & hdu 1443 Joseph(約瑟夫環變形)

poj 1012 & hdu 1443 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


題意:

       共有 k 個壞人 k 個好人坐成一圈(總人數就為2*k),前面的 k 個為好人(編號1~k),後面的 k 個為壞人(編號k+1~2k),

現有一個報數為 m ,從編號為 1 的人開始報數,報到 m 的人會自動的死去。

求當 m 為何值時,可以使在出現有好人死亡前,k 個壞人已經全部死掉?

注意: 當前一輪第 m 個人死後,下一輪的編號為1的人是前一輪編號為 m+1 的人,

前一輪恰好是最後一個人死掉,則下一輪迴圈回到開頭那個人報“1”

k比較小,直接暴力打表!

程式碼如下:
#include <cstdio>
int main()
{
    int p[17], ans[17] = {0};
    int m, k;
    for(k = 1; k <= 14; k++)
    {
        int n = 2*k;//總人數
        m = 1;
        for(int i = 1; i <= k; i++)
        {
            //因為編號是從1開始的
            ans[i] = (ans[i-1]+m-1)%(n-i+1);
            if(ans[i] < k)//說明殺掉了好人,不符合題意
            {
                i = 0;
                m++;//列舉
            }
        }
        p[k] = m;
       // printf("%d\n",p[k]);
    }
   // return 0;
   int kk;
   while(scanf("%d",&kk) && kk)
   {
       printf("%d\n",p[kk]);
   }
   return 0;
}