原题:
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.
题意:
经典的约瑟夫问题,一群人围成一个圈,前k个人是好人,后k个人是坏人,从第一个人开始从1开始报数,每报到n的时候这个人死,然后下一个人继续从1开始报数,直到圈子里剩下的k个人全部都是好人。
题解:
这题之前做过,忘了是poj还是杭电了,看了看以前的代码,发现好像当时测试数据比较少,每输入一个数直接记录,下一次再碰到这个数直接输出结果就行了。
求解方法就是从1穷举,然后加一个数组啊ans[n]表示这一轮死掉的人代号是什么,如果代号小于k,也就是死了好人,就说明报这个数不行,重置报下一个数。
这一轮死的人的代号为ans[i]=(ans[i-1]+m-1)%(n-i+1);就是上一轮的代号加上m-1然后除以剩下的总人数,
这个ans代号的是指每一轮从第一个好人开始数他是第几个,不是最开始的时候这个人在圈里里的序号。
代码:AC
#include<iostream>
using namespace std;
int main()
{
int jose[15]={0};
int k;
while(cin>>k)
{
if(!k)
break;
if(jose[k])
{
cout<<jose[k]<<endl;
continue;
}
int n=2*k;
int ans[20]={0};
int m=1;
int i;
for(i=1;i<=k;i++)
{
ans[i]=(ans[i-1]+m-1)%(n-i+1);
if(ans[i]<k)
{
i=0;
m++;
}
}
jose[k]=m;
cout<<m<<endl;
}
return 0;
}