PAT (Basic Level) Practice (中文)1008 数组元素循环右移问题 (20 分)

时间:2022-07-26
本文章向大家介绍PAT (Basic Level) Practice (中文)1008 数组元素循环右移问题 (20 分),主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

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

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

输入格式:

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

输出格式:

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

输入样例:

6 2
1 2 3 4 5 6

输出样例:

5 6 1 2 3 4

那就是后m个放到前面输出,前n-m放到后面输出~

当然如果m>n时,你会发现每n个数一个循环,所以取m=m%n即可

// luogu-judger-enable-o2
#include<bits/stdc++.h>
#include<unordered_set>
#define rg register ll
#define inf 2147483647
#define min(a,b) (a<b?a:b)
#define max(a,b) (a>b?a:b)
#define ll long long
#define maxn 300005
#define lb(x) (x&(-x))
const double eps = 1e-6;
using namespace std;
inline ll read()
{
	char ch = getchar(); ll s = 0, w = 1;
	while (ch < 48 || ch>57) { if (ch == '-')w = -1; ch = getchar(); }
	while (ch >= 48 && ch <= 57) { s = (s << 1) + (s << 3) + (ch ^ 48); ch = getchar(); }
	return s * w;
}
inline void write(ll x)
{
	if (x < 0)putchar('-'), x = -x;
	if (x > 9)write(x / 10);
	putchar(x % 10 + 48);
}
ll n,k,a[maxn];
queue<ll>q;
int main()
{
    cin>>n>>k;
    for(rg i=1;i<=n;i++)
    {
        ll x=read();
        a[i]=x;
        q.push(x);
    }
    k=k%n;

    k=n-k;
    for(rg i=1;i<=k;i++)
    {
        ll k=q.front();
        q.pop();
        q.push(k);
    }
    while(!q.empty())
    {
        if(q.size()!=1)
        cout<<q.front()<<" ";
        else cout<<q.front();
        q.pop();
    }
    return 0;
}