UVA 305 Joseph

 Joseph 

The Joseph's problem is notoriously known. For those who are not familiar withthe original problem:from among n 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 and m = 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 thefirst k are good guys and the lastk bad guys. You have to determine such minimal m that all the bad guyswill be executed before the first good guy.

Input

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

Output

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

Sample Input

3
4
0

Sample Output

5
30

题目是约瑟夫问题,经典问题 是一群人围一圈,数到第m个杀掉,问最后一个活下来是几号,这是改版,就是找到m,使后一半坏人全死了,前一半一个都没死。
本来想通过找规律,但是好久找不出来,所以还是采用模拟的办法做。因为就1到13.数据量小。
最开始是输入一个k,找一次,然后输出 做出来后超时了,(明明数据量不大的)。。
后来现在开始是把1到13的答案先都算出存在num数组里,输入一个k,就直接输出num[k]这样测试数据如果很多组的话。都只要一开始找一次就好,就过了

AC代码:

#include<stdio.h>


bool kill(int k,int m) {

	int pos = 0;
	for (int i = 0 ; i < k ; i++) {
		pos = (pos + m -1) % (2 * k -i);
		if (pos < k)
			return false;
		
	}
	return true;
}
int main() {

	int k;
	int j;
	int num[14];
    for (int i = 1 ; i <14 ; i++) {
	
		for ( j = 1 ;;j++) {
			if (kill(i,j))
				break;

		}
		num[i] = j;
	}
	while (scanf("%d",&k)) {
	
		if (k == 0)
			break;
		printf("%d\n",num[k]);

	}
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值