poj1012Joseph

Joseph
Time Limit: 1000MS Memory Limit: 10000K
Total Submissions: 56135 Accepted: 21456

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


题意:

有k个坏人k个好人坐成一圈,前k个为好人(编号1~k),后k个为坏人(编号k+1~2k)

现在有一个报数m,从编号为1的人开始报数,报到m的人就要自动死去。

问当m为什么值时,可以使得在出现好人死亡之前,k个坏人先全部死掉?

 

PS:当前一轮第m个人死去后,下一轮的编号为1的人 为 前一轮编号为m+1的人

   前一轮恰好是最后一个人死掉,则下一轮循环回到开头那个人报“1”


 

思路:

经典的约瑟夫水题

 

由于k值比较少(1~13),暴力枚举m就可以了

递推公式为:

ans[i];  //第i轮杀掉 对应当前轮的编号为ans[i]的人(相当于数组下标)

ans[0]=0;

ans[i]=(ans[i-1]+m-1)%(n-i+1);   (i>1  ,  总人数n=2k 则n-i为第i轮剩余的人数)

推导方法:

可以对比一下约瑟夫环公式的推导方法


拿个例子说:K=4,m=30;

f(0)=0;

f(1)=(f(0)+30-1)%8=5; 序列(0,1,2,3,4,5,6,7)中的5

f(2)=(f(1)+30-1)%7=6; 序列(0,1,2,3,4,6,7)中的7

f(3)=(f(2)+30-1)%6=5; 序列(0,1,2,3,4,6)中的6

f(4)=(f(3)+30-1)%5=4; 序列(0,1,2,3,4)中的4


所以只要控制 f(i)>=k 就可以了


ac代码

#include<iostream>
#include<cstdio>
#include<cstring>

using namespace std;

int main()
{
    int k;
    int vis[15] = {0};//已经出现的可以打表记录一下
    while(~scanf("%d",&k) && k)
    {
        int ans[30] = {0};
        if(vis[k])
        {
            printf("%d\n",vis[k]);
            continue;
        }
        int m = 1;
        int n = 2*k;
        for(int i = 1; i <= k; i++)
        {
            ans[i] = (ans[i-1] + m-1)%(n-i+1);//ans[i]表示当前轮被kill人的位置(下标),并不是这个人的编号

            if(ans[i] < k)
            {
                m++;
                i = 0;
            }
        }
            vis[k] = m;
            printf("%d\n",m);
    }
    return 0;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值