Joseph - acm.uva.305(約瑟夫環)

假設有2k個人圍着一個圓桌坐着,前k個是好人,後k個是壞人 。現在開始,每m個人踢掉一個,比如有6個人,m=5,那麼,被踢掉的人依次是5,4,6,2,3,1。現在要求,在踢掉第一個好人前,必需把所有的壞人踢掉,問,給定一個k,求滿足這個要求的最小的m。

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.

這個題目其實就是要求前k次踢掉的都是壞人,假設第i次踢掉的人是i,則i>k。根據題意,可以得到如下關係:
設 ai 是第i次踢掉的人在第i-1次踢掉後剩下的人中是第幾個。那麼

a(n) = [a(n-1)+m-1]mod(2k-n+1)
要求a(n) > k;n = 1,2,3,...,k
其中2k-n+1是第i-1次踢人後剩下的人數。

可以設計如下算法:
bool Joseph(int k, int m) // 這個算法確定對於給定的k,m是否滿足上面的要求
{
    
int n;
    
for(n=1;n<=k;n++)
    
{
        a 
= (a+m-1)%(k2-n+1);
        
if(a == 0) a = k2-n+1;
        
if(a<=&& a>=1return false;
    }

    
return true;
}

然後,我們注意到,第一次踢的人是 m%2k,我們要求 m%2k > k,也就是 m = 2k*r+h,h>k,那麼就可以設計如下的算法找出最小的m:
for(r=0;;r++)
{
    
for(h=k+1;h<=2*k;h++)
    {
         m 
= 2*k*r+h;
         
if(Joseph(k,m)) goto end; // 找到m跳出
     }
}
end: 
發佈了71 篇原創文章 · 獲贊 3 · 訪問量 21萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章