思路:
- 每一个位置存储的数右移应该被存在: next=(current+m)%n ;
- 当不停通过当前位置找下一个位置时,可能形成部分位置的闭合循环,如:int record[6]={0,1,2,3,4,5} 将该序列右移两位有:0->2->4->0 ;1->3->5->1;所以要用 flag[] 标记已经被移动过的位置,当形成闭合环时,找下一个没被标记过的位置重新开始循环;如此往复,直到所有的位置均被标记过,最后正常输出;
代码
#include<cstdio>
using namespace std;
int record[101];
int flag[101]={0};
int n,m;
int main(){
scanf("%d %d",&n,&m);
for(int i=0;i<n;i++)
scanf("%d",&record[i]);
for(int i=0;i<n;i++){
if(flag[i]==0){
int temp1=record[i];
int temp2;
int pos=i;
int next=(pos+m)%n;
while(flag[next]==0){
temp2=record[next];
record[next]=temp1;
temp1=temp2;
flag[next]=1;
pos=next;
next=(pos+m)%n;
}
}
}
for(int i=0;i<n;i++){
printf("%d",record[i]);
if(i!=n-1) printf(" ");
}
return 0;
}