PAT Level B 1008 Array Elements Rotating Right Shift Problem (20 points)

topic content

There are N (>0) integers in an array A. On the premise that other arrays are not allowed, move each integer to the right by M (≥0) cyclically, that is, the data in A is changed from (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 inputs N (1≤N≤100) and M (≥0); the second line inputs N integers, separated by spaces.

Output format:

Output a sequence of integers shifted right by 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

no blank line at the end

Sample output:

5 6 1 2 3 4

no blank line at the end

Problem solving ideas

This kind of problem has a fixed solution, that is, using vector to access the array, on the premise of ensuring m<n (here we can use the method of m=m%n to guarantee), put a[0]-a[n- 1] , a[0]-a[m-1] , a[m-1]-a[n-1] These three paragraphs use the reverse function in sequence ( note that the parameters of the reverse function are left closed and right open ) to reverse their elements.

Detailed code

#include <iostream>
#include <algorithm>   
#include <vector>
using namespace std;
int main() {
    int n, m;
    cin >> n >> m;
    vector<int> a(n); 
    for (int i = 0; i < n; i++){
      cin >> a[i];
    }
    m %= n;   
        reverse(begin(a), begin(a) + n);
        reverse(begin(a), begin(a) + m);
        reverse(begin(a) + m, begin(a) + n);
    for (int i = 0; i < n - 1; i++)
        cout << a[i] << " ";
    cout << a[n - 1];  //解决pat考试中,输出的最后一个数字后不能有空格的问题
    return 0;
}

Guess you like

Origin blog.csdn.net/weixin_45660485/article/details/119274088