51Nod1073-约瑟夫环

基准时间限制:1 秒 空间限制:131072 KB 分值: 0  难度:基础题
 收藏
 关注
N个人坐成一个圆环(编号为1 - N),从第1个人开始报数,数到K的人出列,后面的人重新从1开始报数。问最后剩下的人的编号。
例如:N = 3,K = 2。2号先出列,然后是1号,最后剩下的是3号。
Input
2个数N和K,表示N个人,数到K出列。(2 <= N, K <= 10^6)
Output
最后剩下的人的编号
Input示例
3 2
Output示例
3

详细解法思路见:https://www.cnblogs.com/Ritchie/p/6421282.html

约瑟夫环递推公式:

f(1) = 0;

f(i) = ( f(i-1)+k ) % i      ( i>1 )

以下为代码:

#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;

int main(){
//	freopen( "in.txt","r",stdin );
	int ans,n,k;
	while( ~scanf( "%d %d",&n,&k ) ){
		ans = 0;
		for( int i=2 ; i<=n ; i++ )
			ans = ( ans+k )%i ;
		printf( "%d\n",ans+1 );
	}
	return 0;
}


猜你喜欢

转载自blog.csdn.net/Revenant_Di/article/details/81040656