文章作者:姜南(Slyar) 文章来源:Slyar Home (www.slyar.com) 转载请注明,谢谢合作。
算了,博客不知道发什么,继续刷水题…
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
Slyar:约瑟夫问题都知道了,这个题就是给出一个k,总人数n等于2k,让你找到一个报数m,使得后k个人先出列…
反正k才到14,暴力枚举就行了,不过由于数据比较多,需要开一个数组保存一下才不会超时…
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
#include <iostream> #include <vector> using namespace std; int work(int, int); int main() { int i, k; vector<int> array(14); for (k = 1; k < 14; k++) { for (i = k + 1; ;i += (k + 1)) { if (work(k, i)) { array[k] = i; break; } else if (work(k, i + 1)) { array[k] = i + 1; break; } } } while (1) { cin >> k; if (k == 0) break; cout << array[k] << endl; } return 0; } int work(int k, int m) { int i = 0, len = 2 * k; while (len > k) { i = (i + m - 1) % len; if (i < k) return 0; len--; } return 1; } |
转载请注明:Slyar Home » POJ 1012 Joseph C++版