array element loop right shift problem (20)

Source: Internet
Author: User
Tags gcd greatest common divisor

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 2  1 2 3 4 5 6   Output Sample  :561234  

It is not easy to make a good algorithm because the new array is not required.

Loop right Shift N elements, then minimum complexity should be able to do O (N)

Then the greatest common divisor of M and n can be calculated first GCD

The number of GCD, the moving element, is the number of circle. According to the above example, 6,2 's GCD is 2, the elements in the array are actually divided into two groups to move, 1,3,5 a group, 2,4,6 a group

We can follow this method to design the method of moving.

Finally written out of the program, Time O (N), Space O (1), each CIRCLR only need to move n/gcd+1 secondary elements. The number of moves is probably lower than this.

Paste Code

#include <stdio.h>#include<stdlib.h>intn,m,*A;intgcdintAintb) {  if(a%b==0){    returnb; }  returnGCD (b,a-a/b*b);}intMainvoid) {scanf ("%d%d",&n,&m); M=m%N; A=(int*)malloc(nsizeof(int));  for(intI=0; i<n;i++) {scanf ("%d",&A[i]); }  intTime=gcd (m,n); inttemp,j;  for(intI=0; i<time;i++) {Temp=A[i]; J=i;  while(1) {A[j]=a[(j+n-m)%N]; J= (j+n-m)%N; if(j== (i+m)%N) {A[j]=temp;  Break; }}} printf ("%d", a[0]);  for(intI=1; i<n;i++) {printf ("%d", A[i]); }}

array element loop right shift problem (20)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.