POJ 1012 约瑟夫环

来源:互联网 发布:淘宝刷欢乐豆原理 编辑:程序博客网 时间:2024/06/06 03:39

Joseph
Time Limit: 1000MS Memory Limit: 10000KTotal Submissions: 48092 Accepted: 18144

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

340

Sample Output

530

Source

Central Europe 1995

题意:一群人围成一桌,类似约瑟夫环进行游戏,要求最后留下来的人必须是前k个。

这里整理一下对约瑟夫环的数学方法的理解:

用数学方法解约瑟夫环的关键就是根据当前局面的胜者的标号逆推回上一个局面的胜者标号。
如图,假如一局游戏每次数到第4个人就让他出局,对于一个有4个人的局面,想要知道这个局面的任一个人在新局面的标号,如果将旧标号重复写两遍,可以发现,如果旧标号为x5,新标号为x4,则有x5 = (x4+4)%5。
推广来讲如果当前局面有i个人,胜者在当前局面的编号为xi,每数到第k个人就让他出局,则胜者在i+1个人的局面的标号则为xi+1 = (xi+k)%i(注意当等式右边的值为0时将它修改为i)。


旧标号

1

2

3

4

5

1

2

3

4

5

出局

 

 

 

出局

 

 

 

 

出局

 

新标号

 

 

 

 

1

2

3

4

 

 


于是题就可以解了,枚举k值,直到最后剩下的k个人在2*k个人的局面时的坐标分别为1到k。
直接搞TLE,还得打表。。。
#include <iostream>#include <cstdio>#include <cstdlib>#include <algorithm>#include <ctype.h>#include <cstring>#include <string>#include <queue>#include <cmath>#include <stack>#define MAXN 1110000#define MAXM 1110000#define INF 2100000000#define pu system("pause")#pragma comment(linker, "/STACK:102400000,102400000")using namespace std;int k;int f[] = {2, 7, 5, 30, 169, 441, 1872, 7632, 1740, 93313, 459901, 1358657, 2504881};bool check(int num){    for(int i = 1; i <= k; i++)    {        int pos = i;        for(int j = k+1; j <= 2*k; j++)        {            pos = (pos+num)%j;            if(pos == 0) pos = j;        }        if(pos > k) return 0;    }    return 1;}int main(){//freopen("C:/Users/zts/Desktop/in.txt", "r", stdin);//freopen("C:/Users/zts/Desktop/out.txt", "w", stdout);    while(scanf("%d", &k) != -1 && k)    {        int ans = k, n = 2*k;        /*while(ans++)        {            if(check(ans)) break;        }*/        cout << f[k-1] << endl;    }    return 0;}



0 0
原创粉丝点击