zoukankan      html  css  js  c++  java
  • [POJ1012]Joseph

     
    Time Limit: 1000MS   Memory Limit: 10000K
    Total Submissions: 50596   Accepted: 19239

    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

    THINKING

        本题是约瑟夫环变形 先引入Joseph递推公式,设有n个人(0,...,n-1),数m,则第i轮出局的人为f(i)=(f(i-1)+m-1)%(n-i+1),f(0)=0;

      f(i) 表示当前子序列中要退出的那个人(当前序列编号为0~(n-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

      假设当前剩下i个人(i<=n),显然这一轮m要挂(因为总是从1开始数).经过这一轮,剩下的人是:1 2 3 ... m- 1 m + 1 ... i, 我们将从m+1开始的数映射成1, 则m+2对应2, n对应i - m, 1对应成i - m + 1  m - 1对应i - 1,那么现在的问题变成了已知i - 1个人进行循环报数m,求出去的人的序号。假设已经求出了i- 1个人循环报数下最后一个出去的人的序号X0,那么它在n个人中的序号X1=(X0+ m - 1) % n + 1,  最初的X0=1 ,反复迭代X0和X1可以求出.

      接下来说说m的取值范围:我们考察一下只剩下k+1个人时候情况,即坏人还有一个未被处决,那么在这一轮中结束位置必定在最后一个坏人,那么开始位置在哪呢?这就需要找K+2个人的结束位置,然而K+2个人的结束位置必定是第K+2个人或者第K+1个人,这样就出现两种顺序情况:GGGG.....GGGXB 或  GGGG......GGGBX (X表示有K+2个人的那一轮退出的人)所以有K+1个人的那一轮的开始位置有两种可能即第一个位置或K+1的那个位置,限定m有两种可能:t(k+1) 或 t(k+1)+1; t>=1; 若遍历每一个m必定超时,避免超时则需要打表和限制m的范围。

    const Joseph:array [0..14] of  longint=(0,2,7,5,30,169,441,1872,7632,1740,93313,459901,1358657,2504881,1245064);
    var x:longint;
    begin
        while true do
        begin
        readln(x);
        if x=0 then halt;
        writeln(Joseph[x]);
        end;
    end.
    View Code

     

  • 相关阅读:
    2020软件工程作业02
    2020软件工程作业01
    并发编程—协程
    并发编程—线程
    并发编程—进程
    python网络编程总结
    前端-Javascript
    前端-jQuery
    前端-CSS
    前端-Html
  • 原文地址:https://www.cnblogs.com/yangqingli/p/4889494.html
Copyright © 2011-2022 走看看