zoukankan      html  css  js  c++  java
  • Hdu 1443 Joseph

    Joseph

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


    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
     
    这是一道关于约瑟夫环的问题,题目的大意是总共有2k个伙计围成一圈,1~k是好人,k+1~2k是坏人,报数m,使得k+1~2k的坏人必须在好人之前出去,求出这个m。
     
    很显然,这道题要模拟整个过程,因为题目要求k小于14,所以定义一个一位数组保存所求出的m值。
     
     1 #include <iostream>
     2 using namespace std;
     3 int Joseph(int k,int m)
     4 {
     5     int len = 2*k;
     6     int i;
     7     int n = 1;        //n是要出去的位置,起始位置初始化为1
     8     for (i=1;i<=k;i++)
     9     {
    10         n = (n+m-1)%len;    //第i次出去的人
    11         if(n==0)        //最后一个人出去
    12             n = len;
    13         if(n<=k)            //n小于或等于k时候,返回false
    14             return false;
    15         len--;        //出去一个人,则长度减1
    16     }
    17     return true;
    18 }
    19 
    20 int main()
    21 {
    22     int a[20];
    23     int i,j;
    24     for (i=1;i<15;i++)
    25         for(j=i+1;;j++)
    26             if (Joseph(i,j))
    27             {
    28                 a[i] = j;
    29                 break;
    30             }
    31     int n;
    32     while(cin>>n && n)
    33         cout<<a[n]<<endl;
    34     return 0;
    35 }
    View Code
  • 相关阅读:
    numpy、torch:[ ]里传函数,数组过滤
    torch:torch.sort
    torch : transpose,transpose_
    托管堆和垃圾回收笔记
    UdpClient类客户端和服务端demo
    JavaScript阻止事件冒泡
    单元测试初接触
    CSS选择器
    文档onload处理程序
    TASKKILL命令使用方法
  • 原文地址:https://www.cnblogs.com/yazhou/p/3639165.html
Copyright © 2011-2022 走看看