Uva 305 Joseph(数学+打表)

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 every mthis 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

3
4
0


Sample output

5
30

题目大意:

约瑟夫问题是一道经典的问题,这道问题是约瑟夫问题的改变,大意如下,输入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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值