[原创]我的北大ACM POJ 1012解答
刚开始认为挺简单的,不过做的过程中发现要注意的还挺多。这题一定要储存已经计算过的值,
否则会TLE的。
Source Code
Problem: 1012 | User: absolute | |
Memory: 204K | Time: 47MS | |
Language: C++ | Result: Accepted |
- Source Code
#include <stdio.h>
void POJ1012();
//int result[]={0,2,7,5,30,169,441,1872,7632,1740,93313,459901,1358657,2504881};
int main()
{
POJ1012();
return 0;
}
void POJ1012()
{
int i,k;
int result[14]={0};
scanf("%d",&k);
while(k!=0)
{
// printf("%d\n",result[k]);
int leftguys,m,flag,cur,next;
i=1;
while(true)
{
if(result[k]!=0)
{
printf("%d\n",result[k]);
break;
}
//m为移动的个数,cur为移动前索引,以0为起点
//m只能为k+1的整数倍或者是k+1的整数倍加1,
//因为只剩下K+1个人时,cur索引必位于k或k+1上
m=(k+1)*i;
for(int j=0;j<2;j++)
{
cur=-1;
flag=true;
for(leftguys=2*k;leftguys>k;--leftguys)
{
next = (cur+m)%leftguys;
if(next<k)
{
flag=false;
break;
}
cur = next-1;
}
if(flag)
{
printf("%d\n",m);
result[k]=m;
break;
}
m=(k+1)*i+1;
}
if(flag)
break;
++i;
}
scanf("%d",&k);
}
}