火車進站(陣列、棧、排列組合)
阿新 • • 發佈:2019-01-26
題目描述
給定一個正整數N代表火車數量,0<N<10,接下來輸入火車入站的序列,一共N輛火車,每輛火車以數字1-9編號。要求以字典序排序輸出火車出站的序列號。
輸入描述:
有多組測試用例,每一組第一行輸入一個正整數N(0<N<10),第二行包括N個正整數,範圍為1到9。
輸出描述:
給定一個正整數N代表火車數量,0<N<10,接下來輸入火車入站的序列,一共N輛火車,每輛火車以數字1-9編號。要求以字典序排序輸出火車出站的序列號。
輸入描述:
有多組測試用例,每一組第一行輸入一個正整數N(0<N<10),第二行包括N個正整數,範圍為1到9。
輸出描述:
輸出以字典序從小到大排序的火車出站序列號,每個編號以空格隔開,每個輸出序列換行,具體見sample。
思路:
先排列出所有可能,再判斷是否符合
import java.util.*; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); while (scanner.hasNext()) { int n = scanner.nextInt(); int[] A = new int[n]; for (int i = 0; i < n; i++) A[i] = scanner.nextInt(); ArrayList<int[]> result = new ArrayList<>(); int start = 0; Permutation(A, start, n, result); Set<String> set = new TreeSet<>(); for (int[] out: result) { if (isLegal(A, out, n)) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < n - 1; i++) sb.append(out[i] + " "); sb.append(out[n - 1]); set.add(sb.toString()); } } for (String s: set) System.out.println(s); } } public static boolean isLegal(int[] in, int[] out, int n) { int i = 0; int j = 0; Stack<Integer> stack = new Stack<>(); while (i < n) { if (in[i] == out[j]) { i++; j++; } else { if (stack.isEmpty()) { stack.push(in[i]); i++; } else { int top = stack.peek(); if (top == out[j]) { j++; stack.pop(); } else if (i < n) { stack.push(in[i]); i++; } } } } while (!stack.isEmpty() && j < n) { int top = stack.pop(); if (top == out[j]) j++; else return false; } return true; } //求出所有的排列 public static void Permutation(int[] A, int start, int n, ArrayList<int[]> result) { if (start == n) return; if (start == n - 1) { int[] B = A.clone(); result.add(B); return; } for (int i = start; i < n; i++) { swap(A, i, start); Permutation(A, start + 1, n, result); swap(A, i, start); } } public static void swap(int[] A, int i, int j) { int tmp = A[i]; A[i] = A[j]; A[j] = tmp; } }