Joseph
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 2241 Accepted Submission(s): 1362
Problem 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.
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分析:约瑟夫环果题,打表模板。代码:#include<cstdio> #include<cstring> #include<algorithm> #include<queue> #include<iostream> #include<stack> #include<vector> #include<cstdlib> #define SI(x) scanf("%d",&x) #define PI(x) cout<<x<<endl #define FOR(i,x,n) for(i=x;i<n;i++) #define mem(x,y) memset(x,y,sizeof(x)) #define O_O(x) while(x--) #define SS(x) scanf("%s",x) #define SC(x) cin>>x #define SL(x) cin>>x #define PL(x) cout<<x<<endl #define PS(x) cout<<x<<endl #define PC(x) cout<<x<<endl #define R return #define inf 0x3f3f3f3f #define max(a,b) a>b?a:b #define min(a,b) a<b?a:b using namespace std; int pp[15]; void swap(int a,int b) { if(a>b) { int temp; temp=a; a=b; b=temp; } } int gcd(int a,int b) { R b==0?a:gcd(b,a%b); } int test(int k,int m) { int i,j=0,len=k*2; FOR(i,0,k) { j=(j+m-1)%(len-i); if(j<k) return 0; } return 1; } void joseph() { int m,k; FOR(k,1,15) { m=k+1; while(1){ if(test(k,m)) { pp[k]=m; break; } if(test(k,m+1)) { pp[k]=m+1; break; } m+=k+1; } } } int main() { int k; joseph(); while(SI(k),k) { PI(pp[k]); } R 0; }