hello kity

148078

# HDU 1443( Joseph 约瑟夫问题 )

spoiler posted @ 2011年4月18日 15:36 in 规律及递归经典题 , 3450 阅读

Problem 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


for i : 1 -> 14

for j : i ->

然后分别用长度位2 * i, 周期为 j 的循环模拟，

solve( k ,m ) :

每次都是用 kill = (m - 1)%i （这是求本次需要去除的元素的下标）

更新: start=((start-m)%i+i)%i   ( 其实也可以写成 ：start =( (start - kill -1) %i + i )%i   )

end=((end - m ) % i + i )  % i; 同理也可以写成上面的那样！

示例：

1(0)  2(1)  3(2)  4(3)  5(4)  6(5)

6（0）  1（1）  2（2） 3（3）  4（4）

就这样整个模拟过程的准备工作都完成了！

#include<iostream>
#include<cstdio>
using namespace std;
int f[15];
bool solve(int k,int m){
bool flag=true;
int start=0,end=k-1,kill;
for(int i=2*k;i>k;i--){
kill=(m-1)%i;
//cout<<"i = "<<i<<" "<<"kill = "<<kill<<endl;
if(kill>=start&&kill<=end){
flag=false;
break;
}
start=((start-m)%i+i)%i;
end=((end-m)%i+i)%i;//这样是为了更新起始点，以当前点为0坐标！想象成一个圆形！
//cout<<"start = "<<start<<" "<<" end = "<<end<<endl;
}
return flag;
}

int main(){
int n;
for(int i=1;i<=14;i++){
for(int j=i;;j++){
if(solve(i,j)){
f[i]=j;
break;
}
}
}
while(~scanf("%d",&n),n){
printf("%d\n",f[n]);
}
return 0;
}


kill = ( m - 1 ) % n

start = ( (start - m) % n +n )%n

end = ((end - m )%n +n)% n;

(输入验证码)
or Ctrl+Enter