hdu 1443 Joseph

题目地址:

http://acm.hdu.edu.cn/showproblem.php?pid=1443

题目描述:

Joseph

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 1720    Accepted Submission(s): 1067


Problem 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

题意:

循环走,每次走相同步数都能落到后半段,直至后半段元素全部走过。

题解:

约瑟夫环问题,取余问题。

自己模拟约瑟夫环的循环取余,得出向前走的公式。

代码:

#include
#include
int ans[20]={0};
bool circle[29] = {true};
int k=0,m=0;
int init()
{
    for(k=1;k<=13;k++)
    {
        int n=k+k;
        for(m=k+1;;m++)
        {
            int kill = 0;
            memset(circle, true, sizeof(circle));
            int start = 0;
            while(kill != k)
            {
                int step = m % (n - kill);
                if(step == 0) step = n - kill;
                for(int i=1;i<=step;)
                {
                    start++;
                    if(start>n) start=1;
                    if(circle[start]) i++;
                }
                if(start<=k) break;
                circle[start] = false;
                kill++;
                if(kill==k) break;
                while(circle[start]==false)
                {
                    start--;
                    if(start == 0) start = n;
                }
            }
            if(kill == k) break;
        }
        ans[k]=m;
    }
    return(0);
}
int main()
{
    init();
    while(scanf("%d",&k)!=EOF&&k>0) printf("%d\n",ans[k]);
    return(0);
}






你可能感兴趣的:(ACM_数学,ACM_模拟)