♥HDOJ 1443-Joseph【约瑟夫环+规律】

£神魔★判官ぃ 2022-07-26 00:25 253阅读 0赞

Joseph

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)

Total Submission(s): 2247 Accepted Submission(s): 1366

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

  1. 3
  2. 4
  3. 0

Sample Output

  1. 5
  2. 30

Source

ACM暑期集训队练习赛(5)

解题思路:

保留前面的k个人,报数踢掉后面的人,如果要做到这样我们会注意到,只需要更新最开头的那个数,直到开头那个数大于k。

  1. #include<stdio.h>
  2. #include<string.h>
  3. #include<algorithm>
  4. using namespace std;
  5. int a[1200],b[1200];
  6. int main()
  7. {
  8. int n;
  9. while(scanf("%d",&n)!=EOF)
  10. {
  11. if(n==0)
  12. break;
  13. if(b[n]!=0)
  14. {
  15. printf("%d\n",b[n]);
  16. continue;
  17. }
  18. int i,j;
  19. int k=n;
  20. n=n*2;
  21. int m=1;
  22. a[0]=0;
  23. for(i=1;i<=k;i++)//1~k号是保留的 一直更新a【1】当他比k大时就是我们要找的结果
  24. {
  25. a[i]=(a[i-1]+m-1)%(n-i+1);
  26. if(a[i]<k)
  27. {
  28. m++;
  29. i=0;
  30. }
  31. }
  32. b[k]=m;
  33. printf("%d\n",b[k]);
  34. }
  35. return 0;
  36. }

发表评论

表情:
评论列表 (有 0 条评论,253人围观)

还没有评论,来说两句吧...

相关阅读

    相关

    约瑟夫环 约瑟夫环(约瑟夫问题)是一个数学的应用问题:已知n个人(以编号1,2,3…n分别表示)围坐在一张圆桌周围。从编号为k的人开始报数,数到m的那个人出列;他的下一个

    相关

    N个人坐成一个圆环(编号为1 - N),从第1个人开始报数,数到K的人出列,后面的人重新从1开始报数。问最后剩下的人的编号。 例如:N = 3,K = 2。2号先出列,然后是

    相关

    【问题描述】 编号为 1,2,...,n 的 n 个人按顺时针方向围坐一圈,每人持有一个密码(正整数)。现在给定一个随 机数 m>0,从编号为 1 的人开始,按顺时针方向 1

    相关

    > 约瑟夫环运作如下: > 1、一群人围在一起坐成 \[2\] 环状(如:N) > 2、从某个编号开始报数(如:K) > 3、数到某个数(如:M)的时候,此人出列,

    相关

    约瑟夫环:已知n个人(以编号1,2,3...n分别表示)围坐在一张圆桌周围。从编号为k的人开始报数,数到m的那个人出列;他的下一个人又从1开始报数,数到m的那个人又出列;依此规