008 数组元素循环右移问题 (20分)
一个数组A中存有N(>0)个整数,在不允许使用另外数组的前提下,将每个整数循环向右移M(≥0)个位置,即将A中的数据由(A?0??A?1???A?N?1??)变换为(A?N?M???A?N?1??A?0??A?1???A?N?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<stdio.h>
/*********************************************************************************** 可采用偷懒的写法,直接控制元素的输出。这题可采用三次反转的办法来解题 第一次逆置数组A,第二次逆置数组A的前M个数(原后面的M个数,注意这里的M可能大于N,故需取模)第三次逆置数组A的后N-M个数。某些顺序可调换
*************************************************************************************/
void reverse(int a[], int front, int rear)
{int temp;for(; front < rear; front++, rear--){temp = a[front];a[front] = a[rear];a[rear] = temp;}}int main(void)
{int a[100];int m, n, i = 0; scanf("%d %d", &n, &m);m %= n;while(i < n){ scanf("%d", &a[i++]);};reverse(a, 0, n - 1);reverse(a, 0, m - 1);reverse(a, m, n-1);for(i = 0; i < n - 1; i++) printf("%d ", a[i]);printf("%d\n", a[i]);return 0;
}