1. 题目描述
一个数组A中存有N(>0)个整数,在不允许使用另外数组的前提下,将每个整数循环向右移M(≥0)个位置,即将A中的数据由(A0A1⋯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
2. 分析
写一个逆置函数即可 M=6,N=2
exchange(0,3)变为 4 3 2 1 5 6 exchange(0,M-N-1)
exchange(4,5) 变为 4 3 2 1 6 5 exchange(M-N,M-1)
exchange(0,5)变为 5 6 1 2 3 4 exchange(0,M-1)
3 代码
#include <iostream>
using namespace std;
void reverse(int a[], int s, int e)
{
while(s<e)
{
swap(a[s++],a[e--]);
}
}
int main() {
int M,N;
cin>>M>>N;
int a[M];
for(int i=0;i<M;i++)
{
cin>>a[i];
}
N = N%M;
reverse(a, 0, M - N - 1);
reverse(a, M - N, M - 1);
reverse(a, 0, M - 1);
for(int i=0;i<M-1;i++)
{
cout<<a[i]<<" ";
}
cout<<a[M-1]<<endl;
return 0;
}
3.1 更加简洁的思路
使用reverse库函数
#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;
if (m != 0) {
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];
return 0;
}
4. 收获
reverse函数的编写
void reverse(int a[], int s, int e)
{
while(s<e)
{
swap(a[s++],a[e--]);
}
}
2.reverse函数方法
reverse(begin(a), begin(a) + n)[0,n-1]