zoukankan      html  css  js  c++  java
  • 00-自测3. 数组元素循环右移问题 (20)

    一个数组A中存有N(N>0)个整数,在不允许使用另外数组的前提下,将每个整数循环向右移M(M>=0)个位置,即将A中的数据由(A0 A1……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
    

     1 import java.io.BufferedReader;
     2 import java.io.IOException;
     3 import java.io.InputStreamReader;
     4 
     5 public class Main
     6 {
     7     static int N;
     8     static int M;
     9     static int[] A;
    10     public static void main(String[] args) throws IOException
    11     {
    12 //        System.out.println("...");
    13         BufferedReader buf=new BufferedReader(new InputStreamReader(System.in));
    14         String line=buf.readLine();
    15         String[] temp;
    16         temp=line.split(" ");
    17         N=Integer.parseInt(temp[0]);
    18         M=Integer.parseInt(temp[1]);
    19         M=M%N;
    20         line=buf.readLine();
    21         temp=line.split(" ");
    22         A=new int[temp.length];
    23         boolean[] a=new boolean[temp.length];
    24         for(int i=0;i<A.length;i++)
    25         {
    26             A[i]=Integer.parseInt(temp[i]);
    27             a[i]=false;
    28         }
    29             
    30 //        System.out.println("...");
    31 //        System.out.println(A.length);
    32         if(M==0)
    33             ;
    34         else
    35         {
    36             for(int i=0;i<M;i++)
    37             {
    38                 int t1,t2;
    39                 t1=A[i];
    40                 for(int j=i;a[(j+M)%a.length]==false;j+=M)
    41                 {
    42                     t2=A[(j+M)%A.length];
    43                     A[(j+M)%A.length]=t1;
    44                     t1=t2;
    45                     a[(j+M)%a.length]=true;
    46                 }
    47             }
    48         }
    49         for(int i=0;i<A.length-1;i++)
    50             System.out.print(A[i]+" ");
    51         System.out.println(A[A.length-1]);
    52 
    53         
    54     }
    55 }
  • 相关阅读:
    旧题复习{6}
    CF219D. Choosing Capital for Treeland [树形DP]
    POJ1947 Rebuilding Roads[树形背包]

    洛谷P1280 尼克的任务[DP]
    NOIP2003pj栈[卡特兰数]
    NOIP2001统计单词个数[序列DP]
    洛谷P1415 拆分数列[序列DP 状态 打印]
    POJ2828 Buy Tickets[树状数组第k小值 倒序]
    CF380C. Sereja and Brackets[线段树 区间合并]
  • 原文地址:https://www.cnblogs.com/qq1029579233/p/4398369.html
Copyright © 2011-2022 走看看