题目来源:http://acm.pku.edu.cn/JudgeOnline/problem?id=1012
今天第一次尝试做ACM的题,挑了道看似最简单的Joseph题做,谁知道过程很坎坷啊,提交了n次,终于搞定了。
首先,我常试用一个循环链表的方式做
代码如下:
报错,Limited Memory Exceeded,应该是申请了太多内存空间,没有释放
接下来,我常试用数组做,也是Memory太大,原来是忘了删除每次生成的新数组的空间,后来添加了delete [] p后,又报错,是Time Limited Exceeded
然后我对程序修改了很久,到最后,连数组都没用了,但还是时间太久,后来,看了大家的讨论,发现数据会重复,所以我添加了一个mem[]数组,用以保存先前计算出来的值,下一次还是这个值时,就直接调用,这样就提交成功了
提交成功的代码如下:
但是,总觉得这个方法有点赖皮,高手们还有其它方法吗??
附录:
Joseph
Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 28476 | Accepted: 10625 |
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.
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