Joseph
Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 54077 | Accepted: 20646 |
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
经典的约瑟夫环问题,我的最初想法是直接暴力求解,m的值从k-1开始逐个往下试,直至算出符合要求的m值,输出并跳出循环,但这样对较小的k值(k<10)能比较迅速的算出结果,但当k=10是会有明显卡顿,k>10时会直接卡住,超时代码如下:
#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
int k;
int a[30];
int total=0;
bool joseph(int m)
{
int badGuys=k;
int interval=m;
while(badGuys!=0)
{
m=(m-1)%total;
if(m<k)
return false;
else{
badGuys--;
a[m]=0;
for(int i=0;i<interval;)
{
if(a[((++m)-1)%total]==0)
continue;
else i++;
}
}
}
return true;
}
int main()
{
while(scanf("%d",&k)==1&&k)
{
total=2*k;
for(int m=k-1;;m++)
{
if(m%(k+1)!=0&&m%(k+1)!=1)
continue;
memset(a,1,sizeof(a));
if(joseph(m))
{
printf("%d\n",m);
break;
}
}
}
return 0;
}
后来在网上看别人的博客发现这题是有递推公式的,即:a[i]=(a[i-1]+m-1)%(n-i+1),其中i为当前的轮数,也可以理解为已经杀掉的人的数目,a[i]为要当前要杀掉的人的编号,编号从1开始,于是借助递推公式可以写出以下AC版本:
#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
int a[30];
int ans[15];
int main()
{
int k;
memset(ans,0,sizeof(ans));
while(scanf("%d",&k)==1&&k)
{
if(ans[k])
{
printf("%d\n",ans[k]);
continue;
}
memset(a,0,sizeof(a));
int total=2*k;
int m=1;
for(int i=1;i<=k;i++)
{
a[i]=(a[i-1]+m-1)%(total-i+1);
if(a[i]<k)
{
i=0;
m++;
}
}
ans[k]=m;
cout<<m<<endl;
}
return 0;
}
使用递推公式耗时250ms(一定在暗示我些什么).
其实再看一下题目,k的范围已经明确告诉我们了,为0<k<14,所以我们可以直接打表,所谓打表,即在本地把结果运行出来后再提交,这样也产生了三个版本中最快也最短的代码,耗时16ms,代码如下:
#include <cstdio>
int main()
{
int ans[]={0, 2, 7, 5, 30, 169, 441, 1872, 7632, 1740, 93313, 459901, 1358657, 2504881, 13482720};
int k;
while(scanf("%d",&k)==1&&k)
{
printf("%d\n",ans[k]);
}
return 0;
}