火车进站

来源:互联网 发布:max优化命令英文 编辑:程序博客网 时间:2024/05/16 17:59
package OJ;


import java.util.*;


public class Bully {


/*
* 火车进站
* 先全排列,再输出符合栈规则的项

  * */

private static int cont = 1;

private static ArrayList<String> al = new ArrayList<String>();


public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

while(sc.hasNext()){

int n = Integer.parseInt(sc.nextLine());//输入为火车的总数
int[] str = new int[100];
for(int i=0;i<n;i++)
str[i] = i+1;

perm(str,0,n);


}
}



private static void perm(int[] str, int k, int n) {

if(k==n-1)
print(str,n);//输出项
else{
int temp;
for(int i=k;i<n;i++){
temp = str[k];
str[k] = str[i];
str[i] = temp;

perm(str,k+1,n);

temp = str[i];
str[i] = str[k];
str[k] = temp;
}
}

}




private static void print(int[] str, int n) {

boolean flag = true;
int[] b = new int[2];

for(int i=0;i<n;i++){
int m = 0;
for(int j=i+1;j<n && flag;j++){
if(str[i]>str[j]){
if(m==0)
b[m++] = str[j];
else{
if(str[j]>b[0])
flag = false;
else
b[0] = str[j];
}
}
}
}
if(flag){
sop(cont++ + " ");
for(int i=0;i<n;i++){
sop(str[i]);
}
sop("\n");
}

}




public static void sop(Object o){
System.out.print(o);
}


}
0 0
原创粉丝点击