POJ 1012 Joseph 题解

POJ 1012 Joseph 题解

题目解读:

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.

本道题目的背景是约瑟夫环问题。约瑟夫环是一个数学的应用问题:已知n个人(以编号1,2,3,4…n分别表示)围坐在一张圆桌周围。从编号为k的人开始报数,数到m的那个人出列;他的下一个人又从1开始报数,数到m的那个人又出列;依次规律重复下去,直到圆桌周围的人全部出列。通常解决这类问题时我们把编号从0—n-1,最后结果+1即为原问题的解。
在本道题中对约瑟夫环问题作了一个简单的变形,通过求解最小的报数m,来使得所有的bad guy先于good guy被淘汰。

解决算法

我们在这里假设环的编号从0开始,以下的计算与公式推导均满足这一点。
注意观察到报数m具有延续性,对于n个人而言,第一轮约瑟夫环淘汰了一个人后,剩下的n-1个人其实又组成了一个新的约瑟夫环,唯一区别的就是两个约瑟夫环中的成员编号是不同的。因此,我们可以理解为这里需要解决的是不同编号序列之间的一个映射关系,即将第i+1轮中被淘汰的人的编号映射到第i轮中对应的编号序列。这与动态规划思想中状态转移的思想有相近的地方,因此考虑使用DP算法。现在先给出状态转移方程:

ans[0]=0

ans[i]=(ans[i1]+m1)/(ni+1)i>=1

递归公式推导:
假设有n个人,且报数确定为m。当第一轮编号为m-1(也就是第m个人,这里有一个转换关系)的人出来之后,新的约瑟夫环即需要从第m+1个人起重新编号,这个时候就有新的编号映射关系为:

第i个人 原来的编号 新的编号
(m+1)%n ((m+1)%n-1)%n 0
(m+2)%n ((m+1)%n-1)%n 1
…… …… ……

设n个人围成一个圈的时候被淘汰的是X号,n-1个人围成一个圈的时候被淘汰的是Y号,此处假设Y已经被求出来:
Y=(X*n+n-m)%n
则可以得到反推式:
X=(Y+m-1)%n

代码:

#include<iostream>
#include<vector>

using namespace std;

int final[14]={0};

int Joseph(int k)
{
    int result[14];
    int i,m,n,label=0;
    n=2*k;
    result[0]=0;          //第0轮无淘汰的对象
    m=k+1;                //初始化m
    while(true){
        for(i=1;i<=k;i++){    //前k轮需要被淘汰的序号,这里的序号编号从0开始
            result[i]=(result[i-1]+m-1)%(n-i+1);
            if(result[i]<k){
                label = -1;
                break;
            }
        }
        if(label==-1){
            m++;
            label=0;
        }
        else{
            break;
        }
    }
    return m;
}

int main()
{
    vector<int> input;
    vector<int> output;
    int num=0;
    int k;
    cin>>k;
    while(k!=0){
        input.push_back(k);
        num++;
        cin>>k;
    }
    for(int i=0;i<num;i++){
        if(final[input[i]]!=0){
            output.push_back(final[input[i]]);
        }
        else{
            final[input[i]]=Joseph(input[i]);
            output.push_back(final[input[i]]);
        }
    }
    for(int i=0;i<num;i++){
        cout<<output[i]<<endl;
    }
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章