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.
大意就是:给出k个好孩子和k个坏孩子,好孩子在前,坏孩子在后。然后围成一圈,从第一个开始报数,报到m的退出,求最小的的m满足前k个出局的孩子都是坏孩子。
对于约瑟夫环问题大家的第一影响应该是模拟,数组和链表都行,但是这里如果用不加优化的模拟的话,超时是不可避免的,对于k=13,m是200多万,一个一个枚举,会死人的。。。不过用数组模拟时有个优化,就是m对剩下的人数先取模,也就是说剩下的人数的整数倍对最后的结果不影响。这里可以剪掉很多。还有就是得先把这13个结果算出来,不然还是会超时,因为case居多。。。
下面给出官方的代码(建议先自己想)
官方
1/**//*
2k个好孩子编号从k个坏孩子按顺序围成一个圈,请求出一个最小的m使得按照约瑟夫的规则
3即从当前号开始数数(当前号为1),数到m的人退出,其他人重新重新按顺序围成一个圈,从退出的人之后一个人继续进行下一轮。
4这题要求一个最小的m使得在第一个好孩子出队之前所有的坏孩子都已经出队,也就是所有的坏孩子都要先出队。
5
6显然最直接的方法就是从小到大枚举m的值然后去判定是否满足要求。
7在对确定的m进行判定的时候只需模拟规则即可,复杂度为m*O(模拟)
8因为m比较大所以如果用链表复杂度将会比较大,如果用数组,每次数m下只需取模即可,所以模拟的复杂度会是2*k*k,整个复杂度是O(m*k*k)
9当然由于k最大只有13,一旦发现自己代码超时就应该感觉到,题目可能有重复数据,也就是说可以一次性先算出来,然后O(1)访问,甚至可以本地全部算出来然后打表。
10
11*/
12//Joseph
13#include <iostream>
14using namespace std;
15const int MAXN = 30;
16int n, m, k;
17int man[MAXN], ans[MAXN];
18
19bool ok(){
20 int i, j;
21 for(i = 0; i < n; ++i) man[i] = i;//可以编号k个好孩子为0~k-1,k个坏孩子编号为k~2*k-1
22
23 int p = (m-1+n)%n;
24 i = 0;
25 while(man[p] >= k){
26 // printf("%d ", man[p]);
27 ++i;
28 for(j = p; j < n-1; ++j)//将后面的人往前移动一步
29 man[j] = man[j+1];
30 --n;
31 p = (p+m-1)%n;//当前已经走了一步,再走m-1
32 }
33
34 return i == k;
35}
36
37int main(){
38 for(k = 1; k < 14; ++k){
39 for(m = 1; ; ++m){
40 n = k*2;
41 if(ok()){
42 ans[k] = m;
43 break;
44 }
45 }
46 }
47 while(scanf("%d", &k), k) printf("%d\n", ans[k]);
48 return 0;
49}
50