import java.io.*;
import java.util.*;

public class nextperm_sm implements Runnable {

	BufferedReader br;

	PrintWriter out;

	StringTokenizer st;

	boolean eof = false;

	public void run() {
		try {
			Locale.setDefault(Locale.US);
			br = new BufferedReader(new FileReader("nextperm.in"));
			out = new PrintWriter("nextperm.out");
			solve();
			br.close();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
			System.exit(566);
		}
	}

	public static void main(String args[]) {
		new Thread(new nextperm_sm()).start();
	}

	String nextToken() {
		while (st == null || !st.hasMoreTokens()) {
			try {
				st = new StringTokenizer(br.readLine());
			} catch (IOException e) {
				eof = true;
				return "0";
			}
		}
		return st.nextToken();
	}

	int nextInt() {
		return Integer.parseInt(nextToken());
	}

	long nextLong() {
		return Long.parseLong(nextToken());
	}

	double nextDouble() {
		return Double.parseDouble(nextToken());
	}

	boolean next(int[] a) {
		int j = a.length - 1;

		try {
			while (a[j - 1] > a[j]) {
				j--;
			}
		} catch (ArrayIndexOutOfBoundsException e) {
			return false;
		}
		int min = j;
		for (int i = j; i < a.length; i++) {
			if (a[i] > a[j - 1] && a[i] < a[min]) {
				min = i;
			}
		}
		int tmp = a[j - 1];
		a[j - 1] = a[min];
		a[min] = tmp;
		for (int i = 0; i < (a.length - j) / 2; i++) {
			tmp = a[j + i];
			a[j + i] = a[a.length - 1 - i];
			a[a.length - 1 - i] = tmp;
		}
		return true;
	}

	boolean prev(int[] a) {
		int j = a.length - 1;

		try {
			while (a[j - 1] < a[j]) {
				j--;
			}
		} catch (ArrayIndexOutOfBoundsException e) {
			return false;
		}
		int min = j;
		for (int i = j; i < a.length; i++) {
			if (a[i] < a[j - 1] && a[i] > a[min]) {
				min = i;
			}
		}
		int tmp = a[j - 1];
		a[j - 1] = a[min];
		a[min] = tmp;
		for (int i = 0; i < (a.length - j) / 2; i++) {
			tmp = a[j + i];
			a[j + i] = a[a.length - 1 - i];
			a[a.length - 1 - i] = tmp;
		}
		return true;
	}

	private void solve() {
		int n = nextInt();
		int[] a = new int[n];
		for (int i = 0; i < n; i++) {
			a[i] = nextInt();
		}
		out.println(n);
		if (next(a)) {
			for (int i = 0; i < a.length; i++) {
				out.print(a[i] + " ");
				System.out.print(a[i] + " ");
			}
			out.println();
			System.out.println();
		} else {
			System.exit(1);
		}

	}
}
