1008. Circular right shift of array elements

There are N (N>0) integers in an array A. On the premise that another array is not allowed, move each integer to the right by M (M>=0) positions cyclically, that is, the data in A is replaced by ( A0 A1...AN-1) is transformed into (AN-M...AN-1 A0 A1...AN-M-1) (the last M numbers are cyclically moved to the first M positions). If you need to consider the number of times the program moves data as little as possible, how to design the method of movement?
Input format: each input contains a test case, the first line input N ( 1<=N<=100), M (M>=0); the second line input N integers, separated by spaces.
Output format: output a sequence of integers after cyclic right shift of M bits in one line, separated by spaces, and there must be no extra spaces at the end of the sequence.
Input sample:
6 2
1 2 3 4 5 6
Output sample:
5 6 1 2 3 4
Note: Personally, I prefer to solve these permutation problems with mathematical principles, so students like me must always consider various options. value issue. For example, in my algorithm, when M>N, there will be a problem of obvious array subscript underflow. Therefore, some details should be paid attention to, and more experience can be accumulated by doing more. For example, if the subtraction is considered to be less than 0, equal to 0, or greater than 0; if the addition is considered to be initialized to 0, if the multiplication is considered to be initialized to 1; the denominator of the division cannot be 0. These are all issues to consider.

#include<stdio.h>
int main()
{
    int a[200];
    int i, j, N, M;
    scanf("%d%d", &N, &M);
    if (M>N) M -= N;//后面有N-M的算法所以一定要考虑到表达式小于0的情况
    for (i=0; i<N; i++){
        scanf("%d", &a[i]);
        a[i+N] = a[i];//将前N个值存入后N个空间中去
    }
    for (i=N; i<2*N; i++){//再往回赋值就可避免a[0]=a[1], a[2]=a[1]等轮回赋值的情况
        if (i-(N-M)<N) a[i-N+M] = a[i];//下标不溢出直接赋值
        else a[i-2*N+M] = a[i];//下标溢出则多减去N
    }
    for (i=0; i<N-1; i++)
        printf("%d ", a[i]);
    printf("%d", a[N-1]);//题目要求最后一个不能输出空格,细节!!!
    return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326424115&siteId=291194637