The Josephus Problem(536)

The problem is named after Flavius Josephus, a Jewish historian who participated in and chronicled the Jewish revolt of 66-70C.E. against the Romans. Josephus, as a general, managed to hold the fortress of Jotapata for 47days, but after the fall of the city he took refuge with 40 diehards in a nearby cave. There the rebels voted to perish rather than surrender. Josephus proposed that each man in turn should dispatch his neighbor, the order to be determined by casting lots. Josephus contrived to draw the last lot, and as one of the two surviving men in the cave, he prevailed upon his intended victim to surrender to the Romans. Your task:computint the position of the survivor when there are initially n people.

输入

a Positive Integer n is initially people. n< = 50000

输出

the position of the survivor

样例输入

6

样例输出

5   
在每一轮报数过程中,都有N/K个人退出了队伍,比如N = 10, K = 3,第一轮有N / K = 3三个人退出;
上述第一种方法每次递归的步长为1,这里我们利用上述关系,建立一个步长为N / K的递归过程;
需要注意的是,当N减少到N = K的时候就需要使用第一种递归进行计算;
N > K时的递归公式为:
ret < N mod K: ret = ret - (N mod K) + N
ret >= N mod K: ret = ret - (N mod K) + (ret - N mod K) / (K - 1)
#include
int found(int n)
{
    int m,k;
    if(n==1)
        m=1;
    else
    {
        if(n%2==0)
        {
            k=n/2;
            m=2*found(k)-1;
        }
        else
        {
            k=(n-1)/2;
            m=2*found(k)+1;
        }
    }
    return m;
}

int main()
{
    int n;
    scanf("%d",&n);
    printf("%d\n",found(n));
    return 0;
}

你可能感兴趣的:(算法分析)