題目鏈接:https://pintia.cn/problem-sets/994805260223102976/problems/994805316250615808
題目描述
一個數組A中存有N(>0)個整數,在不允許使用另外數組的前提下,將每個整數循環向右移M(≥0)個位置,即將A中的數據由(A0A1⋯AN−1)變換爲(AN−M⋯AN−1A0A1⋯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 main() {
int n, m, a[10010];
scanf("%d%d", &n, &m);
m = m % n; //m可能比n大
for(int i = 0; i < n; i++)
scanf("%d", &a[i]);
for(int i = n - m; i < n; i++)
printf("%d ", a[i]);
for(int i = 0; i < n - m; i++) {
printf("%d", a[i]);
if(i != n - m - 1)
printf(" ");
}
printf("\n");
return 0;
}
【注】:若不加 m = m % n, 會有兩個case錯誤