题目

一个数组 $A$ 中存有 $N$ ( $>0$ )个整数,在不允许使用另外数组的前提下,将每个整数循环向右移 $M$ ( $\ge 0$ )个位置,即将 $A$ 中的数据由( $A_0 A_1 \cdots A_{N-1}$ )变换为( $A_{N-M} \cdots A_{N-1} A_0 A_1 \cdots A_{N-M-1}$ )(最后 $M$ 个数循环移至最前面的 $M$ 个位置)。如果需要考虑程序移动数据的次数尽量少,要如何设计移动的方法?

输入格式:

每个输入包含一个测试用例,第1行输入 $N$ ( $1\le N \le 100$ )和 $M$ ( $\ge 0$ );第2行输入 $N$ 个整数,之间用空格分隔。

输出格式:

在一行中输出循环右移 $M$ 位以后的整数序列,之间用空格分隔,序列结尾不能有多余空格。

输入样例:

1
2
6 2
1 2 3 4 5 6

输出样例:

1
5 6 1 2 3 4

思路

很简单的一道题,一个需注意的点为M可能大于等于N,需要对N取余再进行接下来的操作。

代码

Github最新代码,欢迎交流

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <stdio.h>

int main()
{
	int N, M, numbers[100];

	scanf("%d %d", &N, &M);
	M %= N; /* M could be larger than N */

	/* Read */
	for (int i = 0; i < N; i++)
		scanf("%d", &numbers[i]);

	/* Print */
	for (int i = N - M; i < N; i++)      /* Print N - M to N - 1 */
		printf("%d ", numbers[i]);
	for (int i = 0; i < N - M - 1; i++)  /* Print 0 to N - M - 2 */
		printf("%d ", numbers[i]);
	printf("%d", numbers[N - M - 1]);   /* Print N - M - 1, no blankspace */

	return 0;
}