zoukankan      html  css  js  c++  java
  • PKU 1012

    Joseph
    Time Limit: 1000MS
    Memory Limit: 10000K
    Total Submissions: 26955
    Accepted: 10073

    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

    Source


    模拟算法肯定能写出来,不过昨天研究了一下约瑟夫的数学解法,发现了一个公式,写出来吧:

    1 int josefus(int n,int m) //n是总人数;m是报的数;返回最后生存的鸟人
    2 {
    3     int i, s=0;
    4     for (i=2; i<=n; i++)
    5     s=(s+m)%i;
    6     return (s+1);
    7 }


    大牛的解法:

    代码
     1 #include<iostream>
     2 using namespace std;
     3 
     4 
     5 int main()
     6 {
     7 int k=0;
     8 int a[14= {0};
     9 while( (cin>>k)&&(k!=0) )
    10 {
    11 if(a[k])
    12 {
    13 cout<<a[k]<<endl;
    14 continue;
    15 }
    16 
    17 for(int m=k+1;;m++)
    18 {
    19 int n=2*k,i=0,flag=0;
    20 while(1)
    21 {
    22 i=(i+m-1)%n;
    23 if(i>=0&&i<k) break;
    24 else flag++;
    25 n--;}
    26 
    27 if(flag==k)
    28 {
    29 a[flag] = m;
    30 cout<<m<<endl;
    31 break;
    32 }
    33 }
    34 
    35 }
    36 
    37 return 0;
    38 }

    这兄弟给了讲解,貌似这一题用了十分取巧的方法:

     http://cid-6d7e68dedf9fc44e.spaces.live.com/blog/cns!6D7E68DEDF9FC44E!130.entry

  • 相关阅读:
    apicloud教程
    apicloud教程3 (转载)
    apicloud教程2 (转载)
    apicloud教程1 (转载)
    API CLOUD 快捷键
    JS IIFE写法
    php事件驱动
    JQuery实践--Why JQuery
    Jquery实践--精读开篇
    python 实践--新闻聚合
  • 原文地址:https://www.cnblogs.com/woodywu/p/1667348.html
Copyright © 2011-2022 走看看