洗牌 我的代码



package xj;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class XiPai {
static int T,N;
static int data[];
static int a[];
static boolean flag;
static int times;
static int X4[][]={
 {0,1,2,3},
 {0,2,1,3},
 {2,0,3,1},
 {2,3,0,1},
};
static int X6[][]={
 {0,1,2,3,4,5},
 {0,1,3,2,4,5},
 {0,3,1,4,2,5},
 {3,0,4,1,5,2},
 {3,4,0,5,1,2},
 {3,4,5,0,1,2},
};
static int X8[][]={
 {0,1,2,3,4,5,6,7},
 {0,1,2,4,3,5,6,7},
 {0,1,4,2,5,3,6,7},
 {0,4,1,5,2,6,3,7},
 {4,0,5,1,6,2,7,3},
 {4,5,0,6,1,7,2,3},
 {4,5,6,0,7,1,2,3},
 {4,5,6,7,0,1,2,3},
};
static int X12[][]={
 {0,1,2,3,4,5,6,7,8,9,10,11},
 {0,1,2,3,4,6,5,7,8,9,10,11},
 {0,1,2,3,6,4,7,5,8,9,10,11},
 {0,1,2,6,3,7,4,8,5,9,10,11},
 {0,1,6,2,7,3,8,4,9,5,10,11},
 {0,6,1,7,2,8,3,9,4,10,5,11},
 {6,0,7,1,8,2,9,3,10,4,11,5},
 {6,7,0,8,1,9,2,10,3,11,4,5},
 {6,7,8,0,9,1,10,2,11,3,4,5},
 {6,7,8,9,0,10,1,11,2,3,4,5},
 {6,7,8,9,10,0,11,1,2,3,4,5},
 {6,7,8,9,10,11,0,1,2,3,4,5},
};
 public static void main(String[] args) throws FileNotFoundException {
  /* Scanner sc=new Scanner(System.in); */
  Scanner sc = new Scanner(new File(“src/XiPai”));
  T=sc.nextInt();
  for (int t = 0; t < T; t++) {
   N=sc.nextInt();
   data=new int [N];
   a=new int [N];
   for (int i = 0; i < N; i++) {
    data[i]=sc.nextInt();
   }
   times=0;
   flag=false;
   if(!isok(data)){
    dfs(0,data);
    if(flag){
     System.out.print(times);
     for (int i = 0; i < N; i++) {
      System.out.print(” “+data[i]);
     }
     System.out.println();
    }
    else{
     System.out.println(-1);
    }
   }
   else{
    flag=true;
    System.out.print(0);
    for (int i = 0; i < N; i++) {
     System.out.print(” “+data[i]);
    }
    System.out.println();
   }
  }
 }
 private static void dfs(int step,int arr[]) {
  if(isok(arr)){flag=true;times=step;
  //成功之后要对全局数组进行改变,好输出;
    for (int i = 0; i < N; i++) {
   data[i]=arr[i];
    }
    return;}
  if(step==5){
   return;
  }
  for (int i = 0; i < N; i++) {//第几种方法,全排列
   //改变顺序
   //这里我用一个数组每次来记录之前的数组值,还进行后续的替换;
   for (int m = 0; m < N; m++) {
    a[m]=arr[m];
         }
    for (int j = 0; j < N; j++) {
     int c=0;
     if(N==4){c=X4[i][j];}
     if(N==6){c=X6[i][j];}
     if(N==8){c=X8[i][j];}
     if(N==12){c=X12[i][j];}
     arr[j]=a[c];
   }
   dfs(step+1,arr);
   if(flag){return;}
  }
 }
 private static boolean isok(int[] arr) {
  int n=0;
  for (int i = 0; i < N-1; i++) {
   if(arr[i]>arr[i+1]){n++;}
  }
  if(n==0||n==N-1){return true;}
  return false;
 }

}

//input

5
4
1 2 3 4
4
4 2 3 1
6
6 5 4 2 3 1
8
6 1 4 7 2 5 8 3
12
2 7 4 1 3 5 8 10 12 9 6 11

//output

0 1 2 3 4
5 4 3 2 1
-1
5 8 7 6 5 4 3 2 1
5 1 2 3 4 5 6 7 8 9 10 11 12

点赞