|
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 |
#include <iostream>
using namespace std;
int a[20];
int main(){
int n;
for(int n=1;n<14;n++){
int nn=2*n;
int k=n;
int flag;
int i=k;
while(1){
if(i%nn==0)
i=i+k;
else
i++;
//i=5;
int p=1;
flag=1;
// cout<<"i:"<<i<<endl;
int q=nn;
for(int j=0;j<n;j++){
p=(p+i-1)%q;
//cout<<q<<" "<<p<<" ";
if(p<=n&&p!=0){
flag=0;
break;
}
if(p==q||p==0)
p=1;
q--;
}
if(flag==1){
break;
}
}
a[n]=i;
}
int m;
while(cin>>m&&m){
cout<<a[m]<<endl;
}
return 0;
}
本文探讨了一个基于经典约瑟夫问题的变形版本,目标是在特定条件下确保所有‘坏人’在第一个‘好人’之前被移除。通过编程实现,文章提供了一种解决方案,并附带示例输入和输出。
1275

被折叠的 条评论
为什么被折叠?



