POJ 1012 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.

translation

约瑟夫问题:n个人围着坐,编号为1~n,从第一个人开始报数,报到第m个数的人被杀死,然后从下一个人接着开始报数,直到只剩下一个人。

例如:n=6,m=5时,出局的顺序为5, 4, 6, 2, 3,1幸运的活了下来。

题目假设一共有2*k个人,前k个为好人,后k个为坏人,要求求出 先出局的k个人 全部为坏人的 最小m。

记得打表,不打表会超时。

这个题目枚举完全可以AC,我看评论区有的人算出来k=1~13时的对应的m,然后直接打印输出。

/*
author:wangqi
url:http://poj.org/problem?id=1012
代码中的字母和题目中的意义一样
思路:人围坐一圈下标为:0-2*k-1;(这样不需要把0换成2*k),注意这里和题目的编号不一样;
从第一次报数开始,用num来记录上一次报数的人的下标
拿k=3,m=5举例   
下标变化为:(0,1,2,3,4,5) -> (0,1,2,3,4) -> (0,1,2,3) -> (0,1,2,3)
删除的人为:删除下标为m-1=4的人,4~5的人变为3~4; 
            删除下标为(4+5-1)%5=3的人,4~4的人变为3~3;
            删除下标为(3+5-1)%4=3的人,此时坏人全部删除。
*/
#include<iostream>
using namespace std;
int main(){
    int m,k,i,result[15] = {0}; //result数组用于打表,猜测有很多重复的
    while(cin>>k && k!= 0){
            if(result[k] != 0){
                cout<<result[k]<<endl;
                continue;
            }
            for(m = k+1;;m++){
                int num = 0;
                for(i = 0 ; i < k; i++){
                    num = (num + m -1)%(2*k-i); //下标
                    if(num < k){ //num<k表示在全部坏人未删除完之前,删除了好人
                        break;
                    }
                }
                if(i == k){
                    cout<<m<<endl;
                    break;
                }
            }
            result[k] = m;
    }
}

阅读更多 登录后自动展开
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页