首页 > 其他 > 详细

HDU 1443 Joseph

时间:2015-09-28 20:55:31      阅读:183      评论:0      收藏:0      [点我收藏+]
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

 

约瑟夫环问题,可以从k+1~2k,2k+k+1~4k。。。因为第一个肯定要删除一个坏人。不断枚举,如果删除了一个好人,则该数不符合,continue,直到剩余人数为k。

经过实验,发现这个细节不用优化,即从i=k+1开始,一直++i,运行时间没有多大影响。

 1 #include<stdio.h>
 2 #include<iostream>
 3 #include<cstring>
 4 
 5 using namespace std;
 6 
 7 int ans[14]={0};
 8 
 9 int joseph(int k)
10 {
11     int cnt,p;
12     if(ans[k])return ans[k];
13     for(int i=k+1;;i++)
14     {
15         for(cnt=2*k,p=0;cnt>k;cnt--)
16         {
17             p=(p+i-1)%cnt;
18             if(p<k)cnt=0;
19         }
20         if(cnt==k)
21         {
22             ans[k]=i;
23             return i;
24         }
25         if(i%(2*k)==0) 
26         {
27             i+=k;
28         }      
29     }
30     return 0;
31 }
32 
33 int main()
34 {
35     int n;
36     while(scanf("%d",&n),n)
37     {
38         printf("%d\n",joseph(n));
39     }
40     return 0;
41 }

 这里再给出原始问题的求解代码。

 1 /* 约瑟夫环问题 */
 2 # include <stdio.h>
 3 int main()
 4 {
 5     int m, n, i, s;
 6  
 7     while (~scanf("%d%d", &m, &n))
 8     {
 9         s = 0;          // F1 = 0;
10         for (i = 2; i <= n; ++i)
11             s = (s + m) % i;
12         printf("%d\n", s+1);       // 原问题的编号是从1开始的
13     }
14  
15     return 0;
16 }

 

HDU 1443 Joseph

原文:http://www.cnblogs.com/Traveller-Leon/p/4844779.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!