1008. array element loop right shift problem ( -)an array a contains n (n>0Integer to move each integer loop to the right by M (m>=), without allowing the use of a different array0The data from a (A0 A1 ...) will be in a position. an-1) Transform to (an-m ... an-1A0 A1 ... an-m-1(the last m-number loop moves to the first m-position). If you need to consider the number of times a program moves data, how do you design a moving method? Input format: Each input contains a test case, and line 1th enters N (1<=n<= -), M (m>=0), line 2nd, enter n integers, separated by a space. Output format: The sequence of integers after the output loop is shifted to the right of the M-bit in a row, separated by a space, with no extra spaces at the end of the sequence. Input Sample:6 21 2 3 4 5 6Sample output:5 6 1 2 3 4
Analysis:
(1) Postgraduate examination 408 has been out of this problem. The practice is to first flip the front 0~n-m-1, and then flip the n-m~n-1, and finally the whole array of the flip, you can not increase the space in the case of the results of the implementation of the problem. It is also important to note that M may be larger than N, at this point, to reduce the unnecessary movement, the M-n remainder, because the loop of an array to move M and m+n the result is the same. The code is as follows:
//The 1:#include <iostream>using namespacestd;voidSwapintA[],int from,intTo ) { while( from<To ) { inttmp; TMP=a[ from]; a[ from]=A[to]; A[to]=tmp; from++; to--; }}intMain () {intn,m; CIN>>n>>m; inta[ the]; M=m%N; for(intI=0; i<n;i++) {cin>>A[i]; } swap (A,0, n-m-1); Swap (A,n-m,n-1); Swap (A,0, N-1); for(intI=0; i<n;i++) { if(i!=0) {cout<<" "; } cout<<A[i]; } cout<<Endl; return 0;}
(2) The second approach is to open an array of 2*n size, followed by a copy of the input array. Output, from the subscript n-m sequentially output n number. The code is as follows:
//The 2:#include <iostream>#include<cstdio>using namespacestd;inta[ -];intMainvoid){ intn,m; CIN>>n>>L; M=m%N; for(intI=0; i<n;i++) {cin>>A[i]; A[i+n]=A[i]; } intindex=n-m; for(intI=0; i<n;i++) { if(i!=0) {cout<<" "; } cout<<A[index]; Index++; } cout<<Endl; return 0;}
1008. Loop right shift of array elements (20)