package org.example.test.practice;

import com.alibaba.fastjson.JSONObject;

import java.util.*;

public class Main { static List<List> all = new ArrayList<>(); static LinkedList path = new LinkedList<>();

// 先回溯算出所有的排列,在检查出站顺序是否合理
public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    while (scanner.hasNextInt()) {
        int n = scanner.nextInt();
        int[] num = new int[n];
        for (int i = 0; i < n; i++) {
            num[i] = scanner.nextInt();
        }
        dfs(num);
        List<List<Integer>> ans = new ArrayList<>();
        for (List<Integer> list : all) {
            if (check(num, list)) {
                ans.add(list);
            }
        }
        Collections.sort(ans, new Comparator<List<Integer>>() {
            @Override
            public int compare(List<Integer> o1, List<Integer> o2) {
                String a = "";
                for (int i = 0; i < o1.size(); i++) {
                    a += o1.get(i);
                }
                String b = "";
                for (int i = 0; i < o2.size(); i++) {
                    b += o2.get(i);
                }
                return a.compareTo(b);
            }
        });
        for (List<Integer> list : ans) {
            for (int i = 0; i < list.size(); i++) {
                System.out.print(list.get(i) + " ");
            }
            System.out.println();
        }
    }
}

private static boolean check(int[] num, List<Integer> list) {
    Deque<Integer> stack = new LinkedList<>();
    int j = 0;
    for (int i = 0; i < num.length; i++) {
        stack.push(num[i]);
        while (!stack.isEmpty() && stack.peek() == list.get(j)) {
            j++;
            stack.pop();
        }
    }
    return stack.isEmpty();
}

private static void dfs(int[] num) {
    if (path.size() == num.length) {
        all.add(new ArrayList<>(path));
        return;
    }
    for (int i = 0; i < num.length; i++) {
        if (!path.contains(num[i])) {
            path.add(num[i]);
            dfs(num);
            path.removeLast();
        }
    }
}

}