2012年9月10日 星期一

uva 305 - Joseph



 Joseph 

The Joseph's problem is notoriously known. For those who are not familiar with the original problem: from among npeople, 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

simulation, linked list

#include<stdio.h>
#define REP(i, b, n) for (int i = b; i < n; i++)
#define rep(i, n) REP(i, 0, n)
#define DBG 1
using namespace std;

int K;
int dp[14],next[28];
void ans(){
int left,m,i,tmp,pn,np,pre;
bool fail;
i=2*K,m=K;
//if(DBG)printf("N %d\n",i);
while(1){
fail=0,m++,left=i;
rep(j,i-1)next[j]=j+1;
next[i-1]=0;
//if(DBG)printf("%d: ",m);
np=0;
while(left>K){
pn=m%left;
if(pn==0)pn=left;
int j=np;
for(tmp=1;tmp++<pn;)pre=j,j=next[j];
//if(DBG)printf(" %d",j);
next[pre]=next[j];
if(j<K){fail=1;break;}
left--;
np=next[j];
}
if(!fail){dp[K]=m;break;}
}
}
void init(){
REP(i,1,14)K=i,ans();
}
int main(){
init();
while(scanf("%d",&K)==1){
if(K==0)break;
printf("%d\n",dp[K]);
}
}

沒有留言:

張貼留言