现在的位置: 首页 > 综合 > 正文

HDU 1443 Joseph 约瑟夫环问题

2018年01月19日 ⁄ 综合 ⁄ 共 1397字 ⁄ 字号 评论关闭

Joseph

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

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
/*
HDOJ 1443
约瑟夫问题 给出K 前K好人 后K坏人 求m 坏人都先出圈 
s=(s+m-1)%n (这里的n指得是剩下的人数)
*/
#include<iostream>
using namespace std;
int a[14];
bool f(int n,int m)
{
    int i,s,k;
    k=n;
    n=n*2;//总人数 
    s=1;
    for(i=1;i<=k;i++)
    {
        s=(s+m-1)%n;
        if(s==0) s=n;
        n--;//总人数递减 
        if(s<=k)//如果是好人 返回 
            return false;
    }
    return true;
}

int main(){
    int i,j,n; 
    for(i=1;i<14;i++)//K大小为14以内 总共2*K的人数 
    {
        for(j=i+1;;j++)//枚举需要的m的大小
                       // 从i+1开始  因为小于i首先必定出去好人 
        {
            if(f(i,j))
            {
                a[i]=j;
                break;
            }
        }
    } 
    while(scanf("%d",&n)&&n) 
    {
        printf("%d\n",a[n]);
    }
    
    return 0;
}

抱歉!评论已关闭.