[TOJ1133]Eeny Meeny Moo 约瑟夫问题

来源:互联网 发布:php 免费云空间 编辑:程序博客网 时间:2024/06/05 14:59

Surely you have made the experience that when too many people use the Internet simultaneously, the net becomes very, very slow.
To put an end to this problem, the University of Ulm has developed a contingency scheme for times of peak load to cut off net access for some cities of the country in a systematic, totally fair manner. Germany's cities were enumerated randomly from 1 ton. Freiburg was number 1, Ulm was number 2, Karlsruhe was number 3, and so on in a purely random order.

Then a number m would be picked at random, and Internet access would first be cut off in city 1 (clearly the fairest starting point) and then in everymth city after that, wrapping around to 1 aftern, and ignoring cities already cut off. For example, ifn=17 andm=5, net access would be cut off to the cities in the order [1,6,11,16,5,12,2,9,17,10,4,15,14,3,8,13,7]. The problem is that it is clearly fairest to cut off Ulm last (after all, this is where the best programmers come from), so for a givenn, the random number m needs to be carefully chosen so that city 2 is the last city selected.

Your job is to write a program that will read in a number of cities n and then determine the smallest integerm that will ensure that Ulm can surf the net while the rest of the country is cut off.

Input Specification

The input file will contain one or more lines, each line containing one integer n with 3 ≤ n < 150, representing the number of cities in the country.
Input is terminated by a value of zero (0) for n.

Output Specification

For each line of the input, print one line containing the integer m fulfilling the requirement specified above.

Sample Input

34567891011120

Sample Output

252431123816


约瑟夫问题描述与解决方案

初始情况: 0, 1, 2 ......n-2, n-1 (共n个人)


第一个人(编号一定是(m-1)%n,设之为(k-1) ,读者可以分m<n和m>=n的情况分别试下,就可以得出结论) 出列之后,

剩下的n-1个人组成了一个新的约瑟夫环(以编号为k==m%n的人开始):

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


现在我们把他们的编号做一下转换:


x' -> x

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


变换后就完完全全成为了(n-1)个人报数的子问题,假如我们知道这个子问题的解:例如x是最终的胜利者,那么根据上面这个表把这个x变回去不刚好就是n个人情况的解吗!


x ->x'(这正是从n-1时的结果反过来推n个人时的编号!)

0 -> k

1 -> k+1

2 -> k+2

...

...

n-2 -> k-2

变回去的公式 x'=(x+k)%n


那么,如何知道(n-1)个人报数的问题的解?只要知道(n-2)个人的解就行了。(n-2)个人的解呢?只要知道(n-3)的情况就可以了 ---- 这显然就是一个递归问题:


令f[i]表示i个人玩游戏报m退出最后胜利者的编号,最后的结果就是f[n]


递推公式


f[1]=0;

f[i]=(f[i-1]+k)%i = (f[i-1] +m%i) % i = (f[i-1] + m) % i ;  (i>1)


解题思想:有n个城市,第一个总是最先退出,相当于从第二个开始按1,2,……m,1,2……m这样报数,问题实际上可抽象成n-1个城市的Josephus问题,注意josephus思想是按0,1,……n-1编号的,又加上是从第二个城市开始报数,求得的最后一个城市的实际编号=Josephus方法求得的编号+1+1。

result == 0 时为所求。

#include <cstdio>#include <iostream>#include <cstdlib>using namespace std;int main(){int n;while (cin >> n && n){int m;for (m = 2;;m++){int result = 0;for (int i = 2;i < n;i++){result = (result + m ) % i ;}//cout << result << endl;if (result == 0) {cout << m << endl;break;}}}return 0;}