題目鏈接:https://pintia.cn/problem-sets/994805260223102976/problems/994805316250615808
題目描述
一個數組A中存有N(>0)個整數,在不允許使用另外數組的前提下,將每個整數循環向右移M(≥0)個位置,即將A中的數據由(A0 A1 ⋯AN−1 )變換爲(AN−M ⋯AN−1 A0 A1 ⋯AN−M−1 )(最後M個數循環移至最前面的M個位置)。如果需要考慮程序移動數據的次數儘量少,要如何設計移動的方法?
輸入
每個輸入包含一個測試用例,第1行輸入N(1≤N≤100)和M(≥0);第2行輸入N個整數,之間用空格分隔。
輸出
在一行中輸出循環右移M位以後的整數序列,之間用空格分隔,序列結尾不能有多餘空格。
樣例輸入
6 2
1 2 3 4 5 6
樣例輸出
5 6 1 2 3 4
代碼
#include <cstdio>
int gcd(int a, int b) {
if(b == 0)
return a;
else
return gcd(b, a % b);
}
int main() {
int a[110];
int n, m, temp, pos, next;
scanf("%d%d", &n, &m);
for(int i = 0; i < n; i++)
scanf("%d", &a[i]);
m = m % n;
if(m != 0) {
int d = gcd(m, n);
for(int i = n - m; i < n - m + d; i++) {
temp = a[i];
pos = i;
do{
next = (pos - m + n) % n;
if(next != i)
a[pos] = a[next];
else
a[pos] = temp;
pos = next;
}while(pos != i);
}
}
for(int i = 0; i < n; i++) {
printf("%d", a[i]);
if(i < n - 1)
printf(" ");
}
return 0;
}