【PAT B 1008】数组循环右移问题

本题有两种思路:一种就是本办法,一位一位的移动。另一种就是直接计算要输入位置的数组下标,然后在这个位置进行输入。程序的思路就点小技巧,数组移动需要一个空位置,直接将头元素拿下来或者把尾元素拿下来。左移时就拿尾元素,右移就拿掉头元素,然后循环移动。注意进行的移位操作没有说明小于数组大小,所以要先进行取余运算,防止操作过多出现TLE错误。

#include <iostream>
#include <cmath>
using namespace std;
const int maxn = 1005;

void OneByteRight(int list[],int size){
    int temp;
    temp = list[size - 1];
    for(int i = size - 2;i >= 0;i--)
        list[i + 1] = list[i];
    list[0] = temp;
}

int main(void){
    int list[maxn] = {0},space = 0;
    int size,operations;
    cin >> size >> operations;
    space = size - 1;
    operations %= size;
    for(int i = 0;i < size;i++)
        cin >> list[i];

    for(int i = 0;i < operations;i++)
        OneByteRight(list,size);

    for(int i = 0;i < size;i++) {
        cout << list[i];
        if(space)
            cout << ' ';
        space--;
    }
    return 0;
}

另一种思路是直接计算出原数列头元素右移操作后的位置,然后从这个位置进行输入操作。循环操作就是利用取余运算符,到达size时返回0。但注意实际标号要和size差一位才行。

本题先计算出实际要移动的位数bit,因为整数和数组下标差1,直接作为输入的起始坐标,一共有number个数,小于number + bit,或者小于等于number + bit - 1。

#include <iostream>
using namespace std;
const int maxn = 105;
int main(){
    int number,bit,list[maxn] = {0},space = 0;
    cin >> number >> bit;
    bit = bit % number;
    space = number - 1;
    for(int i = bit;i < number + bit;i++){
        cin >> list[i % number];
    }
    for(int i = 0;i < number;i++) {
        cout << list[i];
        if (space--)
            cout << ' ';
    }
    return 0;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容