Title Description
An array A contains N (n>0) integers, and each integer loop is shifted to the right by M (m>=0), and the data from a (A0 A1 ...) is not allowed to use a different array . AN-1) transform to (an-m ... AN-1 A0 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 Description:
Each input contains a test case, line 1th enters N (1<=n<=100), M (m>=0), and line 2nd enters n integers, separated by a space.
Output Description:
In a row, the output loop shifts the M-bit after the integer sequence, separated by a space, with no extra spaces at the end of the sequence.
Input Example:
6 2
1 2 3 4 5 6
Output Example:
5 6 1 2 3 4
1 intSize,count;2CIN >> Size >>count;3 inta[ $] ={0};4 intNums = count%size;5 for(intI=0; i<size;++i)6 {7CIN >>A[i];8 if(Nums = =size)9Nums =0;Tena[ -+ (nums++)] =A[i]; One } A for(intI=0; i<size;++i) -cout << a[i+ -] <<' ';
As previously written, define an array of 200 directly and move the array back to the back half of the array. But with the help of the memory outside.
Due to the upper red letter limit. moving an element inside an array is bound to overwrite the elements of the current position , and it is illegal to save the elements that are about to be overwritten with other memory. So here we need to find a better alternative, the use of three times reverse operation, to achieve "mobile", the time and space complexity of not more than O (n).
Principle:
The inverted operation of the array is also simple, with the values of the tail-pointing pointer interchanged until two pointers intersect.
AC Code:
#include <iostream>using namespacestd;classsolutions{ Public: voidReverseintArr[],intPrevintBack ) { inttmp; while(prev<Back ) {tmp=Arr[back]; Arr[back]=Arr[prev]; Arr[prev]=tmp; ++prev; --Back ; } } voidPrintintArr[],intPrevintBack ) { for(inti=prev;i<back;++i) {cout<<Arr[i]; if(i!=back-1) cout<<' '; } }};intMain () {Solutions s; intSize,number; CIN>> size >>Number ; inta[ -]; for(intI=0; i<size;++i) Cin>>A[i]; number= number%size; S.reverse (A,0, size-1-Number ); S.reverse (A,size-number,size-1); S.reverse (A,0, size-1); S.print (A,0, size);}
Loop right shift problem for array elements