PAT Basic 1008

1008 数组元素循环右移问题 (20 分)

一个数组A中存有N(>0)个整数,在不允许使用另外数组的前提下,将每个整数循环向右移M(0)个位置,即将A中的数据由(A0​​A1​​AN1​​)变换为(ANM​​AN1​​A0​​A1​​ANM1​​)(最后M个数循环移至最前面的M个位置)。如果需要考虑程序移动数据的次数尽量少,要如何设计移动的方法?

输入格式:

每个输入包含一个测试用例,第1行输入N(1N100)和M(0);第2行输入N个整数,之间用空格分隔。

输出格式:

在一行中输出循环右移M位以后的整数序列,之间用空格分隔,序列结尾不能有多余空格。

输入样例:

6 2
1 2 3 4 5 6

输出样例:

5 6 1 2 3 4

注意,m可能会大于n,另外,直接不移动数组写个方法偏移输出也是可以的
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include <vector>
#include<algorithm>
#include<string>
#include<math.h>
#define max 1000
#define debug 0
using namespace std;

void reverse(int a[], int n, int begin, int end)
{
    int temp = 0;
    if (begin >= end)
        return;
    for (int i = begin; i <=(begin + end)/2; i++)
    {
        temp = a[i];
        a[i] = a[end - i+begin];
        a[end - i + begin] = temp;
    }
}

int main() {
#if debug
    freopen("in.txt", "r", stdin);
#endif

    int n, m,a[max];
    cin >> n >> m;
    m = m%n;
    for (int i = 0; i < n; i++)
    {
        cin >> a[i];
    }
    reverse(a, n, 0, n - 1 - m);
    reverse(a, n, n-m, n-1);
    reverse(a, n, 0, n-1);
    for (int i = 0; i < n-1; i++)
    {
        cout << a[i] << ' ';
    }
    cout << a[n - 1];

#if debug
    freopen("CON", "r", stdin);
#endif
    return 0;
}

原文链接: https://www.cnblogs.com/lxzbky/p/10498505.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

    PAT Basic 1008

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/400178

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年4月14日 上午9:45
下一篇 2023年4月14日 上午9:46

相关推荐