In computer science and mathematics, the Josephus Problem (or Josephus permutation) is a theoretical problem related to a certain counting-out game.
There are people standing in a circle waiting to be executed. The counting out begins at some point in the circle and proceeds around the circle in a fixed direction. In each step, a certain number of people are skipped and the next person is executed. The elimination proceeds around the circle (which is becoming smaller and smaller as the executed people are removed), until only the last person remains, who is given freedom.
The task is to choose the place in the initial circle so that you are the last one remaining and so survive.
以上摘自Wiki,关于更多“约瑟夫问题”的细节可以参考http://en.wikipedia.org/wiki/Josephus_problem。
本来想用循环链表来实现,如果只是找出最后一个获胜的人可行。但是因为需要找到能够获胜的位置,所以直接用数组实现相对简单。
#include "stdio.h"
#define LEN 40
#define K 3
int main(){
int man[LEN] = {0};
int n = -1;
int winner;
printf("the number of mans is: %d\nthe skipped number k is: %d\n", LEN, K);
for (int i = 0; i < LEN; ++i){
int count = 0;
while (count <= K){
n = (n+1)%LEN;
if (man[n] == 0){
++count;
}
}
man[n] = i+1;
if (i == LEN-1){
winner = n+1;
}
}
printf("the Josuphus Sort are: \n");
for (int i = 0; i < LEN; ++i){
printf("%d ", man[i]);
}
printf("\nthe winner is: %d\n", winner);
}
output:
本文介绍约瑟夫问题的背景及解决方法,并通过一个C语言程序实例演示如何求解该问题,找出最终生存者的位置。

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



