Joseph
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 Source |
普通的模拟过程会超时,需要计算n个人的环,每报m个数出列的人序号的公式。n个人分别编号0……(n-1)
第一个出列的人的序号f1=(m-1)%n
第二个出列的人的序号f1=(f1+m-1)%(n-1)
第i个出列的人的序号fi=((fi-1)+m-1)%(n-i+1)
然后就没什么问题了。。。
#include <iostream>
using namespace std;
int ans[15]={0},x,n,f[15]={0};
int joseph(int x){
int m=x,i;
while (m++){
for (i=1;i<=x;++i){
f[i]=(f[i-1]+m-1)%(n-i+1);
if (f[i]<x) break;
}
if (i>x){
ans[x]=m;
return m;
}
}
}
int main()
{
while (cin>>x && x){
if (ans[x]) cout<<ans[x]<<endl;
else{
n=x*2;
cout<<joseph(x)<<endl;
}
}
return 0;
}
kdwycz的网站: http://kdwycz.com/
kdwyz的刷题空间:http://blog.csdn.net/kdwycz