codevs1282 约瑟夫问题
题目描述 Description
有编号从1到N的N个小朋友在玩一种出圈的游戏。开始时N个小朋友围成一圈,编号为I+1的小朋友站在编号为I小朋友左边。编号为1的小朋友站在编号为N的小朋友左边。首先编号为1的小朋友开始报数,接着站在左边的小朋友顺序报数,直到数到某个数字M时就出圈。直到只剩下1个小朋友,则游戏完毕。
现在给定N,M,求N个小朋友的出圈顺序。
输入描述 Input Description
唯一的一行包含两个整数N,M。(1<=N,M<=30000)
输出描述 Output Description
唯一的一行包含N个整数,每两个整数中间用空格隔开,第I个整数表示第I个出圈的小朋友的编号。
样例输入 Sample Input
5 3
样例输出 Sample Output
3 1 5 2 4
//此时位置与维护前缀和,线段树比队列快很多,Is not it?
#include<bits/stdc++.h>
using namespace std;
int n,m,A[100010],k,t;
void buildtree(){
for(int i=t-1;i>0;i--)A[i]=A[i*2]+A[i*2+1];
}
void update(int L,int R,int o,int x){
if(L==R)A[o]=0;
else {
int M=L+(R-L)/2;
if(M>=x)update(L,M,o*2,x);
else update(M+1,R,o*2+1,x);
A[o]=A[o*2]+A[o*2+1];
}
}
int find(int L,int R,int o,int now){
if(L==R){return L;}
int M=L+(R-L)/2;
if(now<=A[o*2])return find(L,M,o*2,now);
return find(M+1,R,o*2+1,now-A[o*2]);
}
int main(){
scanf("%d%d",&n,&m);
while((1<<k)<n)k++;
t=1<<k;
for(int i=t;i<t+n;i++)A[i]=1;
buildtree();
int now=1;
for(int i=n;i>0;i--){
now=(now+m-2)%i+1;
int x=find(1,t,1,now);
printf("%d ",x);
update(1,t,1,x);
}
puts("");
return 0;
}

浙公网安备 33010602011771号