# 算法分析实验之The Josephus Problem（约瑟夫问题）

03/23 15:13

## 题目描述

The problem is named after Flavius Josephus, a Jewish historian who participated in and chronicled the Jewish revolt of 66-70C.E. against the Romans. Josephus, as a general, managed to hold the fortress of Jotapata for 47days, but after the fall of the city he took refuge with 40 diehards in a nearby cave. There the rebels voted to perish rather than surrender. Josephus proposed that each man in turn should dispatch his neighbor, the order to be determined by casting lots. Josephus contrived to draw the last lot, and as one of the two surviving men in the cave, he prevailed upon his intended victim to surrender to the Romans. Your task:computint the position of the survivor when there are initially n people.

## 输入

``a Positive Integer n is initially  people. n< = 50000``

## 输出

``the position of the survivor``

## 样例输入复制

``6``

## 样例输出

``5据说著名犹太历史学家 Josephus有过以下的故事：在罗马人占领乔塔帕特后，39 个犹太人与Josephus及他的朋友躲到一个洞中，39个犹太人决定宁愿死也不要被敌人抓到，于是决定了一个自杀方式，41个人排成一个圆圈，由第1个人开始报数，每报数到第3人该人就必须自杀，然后再由下一个重新报数，直到所有人都自杀身亡为止。然而Josephus 和他的朋友并不想遵从。首先从一个人开始，越过k-2个人（因为第一个人已经被越过），并杀掉第k个人。接着，再越过k-1个人，并杀掉第k个人。这个过程沿着圆圈一直进行，直到最终只剩下一个人留下，这个人就可以继续活着。问题是，给定了和，一开始要站在什么地方才能避免被处决？Josephus要他的朋友先假装遵从，他将朋友与自己安排在第16个与第31个位置，于是逃过了这场死亡游戏。``

k k+1 k+2 ... n-2,n-1,0,1,2,... k-2

k --> 0
k+1 --> 1
k+2 --> 2
...
...
k-2 --> n-2

f[1]=0;
f[i]=(f[i-1]+m) mod i; (i>1）

``因为题目说的是报数到3的自杀，所以报数最多只能进行到2，m=2``
``````#include <iostream>
using namespace std;
const int m = 2;
int main()
{
int n, f = 0;
cin >> n;
for (int i = 1; i <= n; i++) f = (f + m) % i;
cout << f + 1 << endl;
}``````

0
0 收藏

0 评论
0 收藏
0