zoukankan      html  css  js  c++  java
  • Programming Ability Test学习 1008. 数组元素循环右移问题 (20)

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

    时间限制
    400 ms
    内存限制
    65536 kB
    代码长度限制
    8000 B
    判题程序
    Standard

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

    输入格式:每个输入包含一个测试用例,第1行输入N ( 1<=N<=100)、M(M>=0);第2行输入N个整数,之间用空格分隔。

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

    输入样例:
    6 2
    1 2 3 4 5 6
    
    输出样例:
    5 6 1 2 3 4
    

    提交代码

    解题思路:如果要向右移动M位,就将数组的后M位逆序,再将剩余的逆序,然后数组全部元素逆序。如果M大于数组容量N,则取M=M%N。

    #include<iostream>
    #include<cstdio>
    #include<cmath>
    #include<cstdlib>
    #include<cstring>
    #include<string>
    #include<algorithm> 
    #define MAXSIZE 100005
    using namespace std;
    
    //逆序函数
    void invert_Func(int *a,int front,int rear)
    {
        int i,j;
        for(i=front,j=rear;i<j;i++,j--)
        {
            a[i]=a[j]-a[i];
            a[j]=a[j]-a[i];
            a[i]=a[j]+a[i];
        }
    } 
    
    //循环M位函数
    void goMright(int *a,int N,int M)
    {
        M=M%N;
        invert_Func(a,0,N-M-1);
        invert_Func(a,N-M,N-1);
        invert_Func(a,0,N-1);
    } 
    int main()
    {
        int N,M;
        scanf("%d %d",&N,&M);
        int *a=new int[N];
        for(int i=0;i<N;i++)cin>>a[i];
        goMright(a,N,M);
        for(int i=0;i<N;i++){
        cout<<a[i];
        if(i==N-1)cout<<endl;
        else cout<<" ";
        }
        return 0;
    } 
  • 相关阅读:
    Spring boot 启动图片
    Spring Cloud 从入门到入门
    理解错误的 Arrays.asList()
    git github 对代码的管理
    【POJ 2154】Color
    CodeForces
    CodeForces
    CodeForces
    CodeForces
    [数据结构]Hash Table(哈希表)
  • 原文地址:https://www.cnblogs.com/a842297171/p/4775587.html
Copyright © 2011-2022 走看看