您的位置:首页 > 其它

poj_1012joseph

2014-12-16 17:29 323 查看
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
3
4
0

Sample Output
5
30


Source
//joseph问题是将一群人围成一个圈,数到谁就杀掉谁,杀掉的被排除,继续执行直到k-2*k-1 共k个坏人死且0-k-1没人死为止最小的数,首先可以从中推出关系此个被杀与下个被杀的号数,然后继续找,有一条不同跳出循环,起始选定个数时要排除不行的


#include "iostream"

using namespace std;

int main()

{

int n;

cin>>n;

while(n!=0)

{ int stnum=2;//执行的个数

int sttimes=0;//执行的次数

int *a=new int [2*n];

memset(a,0,2*n*sizeof(int));//零为没被杀

int st=1;

int killno=-1;//死的号数

int flag=1;//标志

while((stnum%(2*n))<n)

stnum++;

while(1)

{while((stnum%(2*n))<n)

stnum++;

while(a[0]!=1)

{ if(st==1)

{st=0;killno=(killno+stnum)%(2*n);a[killno]=1;}

else

{ sttimes=0;

while(sttimes!=stnum)//跳过的人头数

{ while(a[killno]==1)

{

killno=(killno+1)%(2*n);

}

sttimes++;

killno=(killno+1)%(2*n);

}

if(killno==0)

killno=2*n-1;

else

killno=(killno-1)%(2*n);

a[killno]=1;//杀死

}

if(killno<n)

goto si;

for(int i=n;i<2*n;i++)

{

if(a[i]==0)//只要一个没被杀 flag 变1

{

flag=1;

break;

}

}

if(flag==0)//可以的情况

{

goto fi;

}

flag=0;

}

si:

memset(a,0,2*n*sizeof(int));//零为没被杀

stnum++;

st=1;//第一个

killno=-1;

flag=1;

}

fi:

cout<<stnum<<endl;

cin>>n;

}

return 0;

}

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