您的位置:首页 > 其它

UVA 305 Joseph

2014-07-15 10:43 302 查看



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;
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: