您的位置:首页 > 编程语言

[POJ][1012]Joseph

2014-05-14 22:42 316 查看
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


joseph问题用数组或者链表模拟起来比较麻烦,而且很容易就TLE了,最好的方法还是找规律

我自己在纸上慢慢推导的公式在下面

f[i]表示第i轮被抽杀的人的序号,序号从0开始,m表示抽杀用的数字,n表示最开始的总人数

设 f[0] = 0

f[i] = (f[i-1]+m-1)%(n-i+1) 其中i>0

代码的思路如下

设置一个大小为14的int数组,用来存抽杀递推数组,因为抽杀的递推公式计算时需要前面一次的数据

然后读入一个k,初始化抽杀数字m=k+1,因为之前的数字第一个抽杀好人,直接不用管了,用m进行一轮抽杀,如果发现f[i]<k,就是说好人死了,直接m++重新抽杀.如果k轮抽杀都没有傻叼好人,那么这个m符合要求,输出

注意POJ上面如果你仅仅是这么写的话会TLE,主要是因为POJ的测试数据使用了重复的数字,所以我们设置一个大小为13或者14的数组存放k对应的正确的m,也就是在线打表,把计算过的答案存起来,再遇到直接输出答案.

下面是AC代码,代码中比较巧妙的是对重新抽杀的处理,也就是直接让i=0,然后就可以重新从i=1开始抽杀了

#include <iostream>
using namespace std;
int main()
{
int k=0,joseph[14]={0},ans[14]={0};
while (cin>>k) {
if (k == 0) break;
if (ans[k]) {
cout<<ans[k]<<endl;
continue;
}
int n=2*k,m=k+1;
for (int i=1;i<=k;i++) {
joseph[i] = (joseph[i-1]+m-1) % (n-i+1);
if (joseph[i]<k) {
i=0;
m++;
}
}
ans[k]=m;
cout<<m<<endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  poj 源代码