Uva 305 Joseph(数学+打表)

来源:互联网 发布:mac u盘图标 编辑:程序博客网 时间:2024/06/07 17:10

Joseph


The Joseph's problem is notoriously known. For those who are not familiar withthe original problem:from amongn people, numbered 1, 2, ...,n, standing in circle everymthis going to be executed and onlythe life of the last remaining person will be saved. Joseph was smart enoughto choose the position of thelast remaining person, thus saving his life to give us the message aboutthe incident. For example whenn = 6 andm = 5 then the people will be executed in the order5, 4, 6, 2, 3 and 1 will be saved.

Suppose that there are k good guys and k bad guys. In the circle thefirstk are good guys and the lastk bad guys. You have to determine such minimalm that all the bad guyswill be executed before the first good guy.


The input file consists of separate lines containing k. The last line inthe input file contains 0. You can suppose that 0 <k < 14.


The output file will consist of separate lines containing m correspondingtok in the input file.


Sample input

340


Sample output

530

题目大意:

约瑟夫问题是一道经典的问题,这道问题是约瑟夫问题的改变,大意如下,输入k代表队伍的前排有k个好人,后排有k个坏人,你要做的是找出最小的点名数。

其公式如下 ans[i+1] = (ans[i] + m - 1) % (n - i)

m代表点名数,n代表总人数


#include<iostream>#include<math.h>#include<stdio.h>#include<string.h>using namespace std;const int N = 20;int ans[N];int k;bool Joseph(int n,int m) { //n为总人数,m为要枪毙的数ans[1] = (m - 1) % n;k = n/2;if(ans[1] < k)return false;for(int i=1;i<k;i++) {ans[i+1] = (ans[i] + m - 1) % (n - i);if(ans[i+1] < k)return false;}return true;}int main() {int k;while(scanf("%d",&k) != EOF ,k) {memset(ans,0,sizeof(ans));for(int i=k;;i++) {if(Joseph(2*k,i)) {printf("%d\n",i);break;}}}return 0;}

但是以上的代码超时

所以只能打表AC代码如下


#include<stdio.h>const int N=20;int main() {int k;int ans[N]={0,2,7,5,30,169,441,1872,7632,1740,93313,459901,1358657,2504881};while(scanf("%d",&k)!=EOF,k) {printf("%d\n",ans[k]);}return 0;}


0 0
原创粉丝点击