约瑟夫环
N个人坐成一个圆环(编号为1 - N),从第1个人开始报数,数到K的人出列,后面的人重新从1开始报数。问最后剩下的人的编号。
例如:N = 3,K = 2。2号先出列,然后是1号,最后剩下的是3号。
2个数N和K,表示N个人,数到K出列。(2 <=N, K <= 10^6)
Output最后剩下的人的编号
Sample Input3 2Sample Output
3
代码均为转载:http://blog.csdn.net/acdreamers/article/details/17686829
上面有见解。
其一代码如下:
#include<iostream>
#include<cstdio>
using namespace std;
int main()
{
int t,n,k,i,p=1;
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&n,&k);
printf("Case #%d:",p++);
printf(" %d %d",2*k,k);
for(i=k-1;i>=1;i--)
printf(" %d",i);
for(i=k+1;i<=n;i++)
if(i!=2*k)
printf(" %d",i);
puts("");
}
return 0;
}
其二代码如下:
#include <iostream>
#include <string.h>
#include <stdio.h>
using namespace std;
typedef long long LL;
LL Work(LL n,LL m,LL k)
{
if(m == 1)
k = (k == 1 ? n:(n+k-1)%n);
else
{
for(LL i=1; i<=n; i++)
{
if(k + m < i)
{
LL x = (i-k+1)/(m-1) - 1;
if(i + x < n)
{
i += x;
k += m*x;
}
else
{
k += m*(n-i);
i = n;
}
}
k = (k+m-1)%i+1;
}
}
return k;
}
int main()
{
LL n,k;
while(cin>>n>>k)
cout<<Work(n,k,1)<<endl;;
return 0;
}

浙公网安备 33010602011771号