// Arup Guha
// 12/3/2016
// Written to illustrate custom sorting the same data in two ways.

import java.util.*;

public class customsort3 {

	public static void main(String[] args) {

		// Get the number of students.
		Scanner stdin = new Scanner(System.in);
		int n = stdin.nextInt();

		// Create and sort the student objects.
		student[] list = new student[n];
		for (int i=0; i<n; i++)
			list[i] = new student(stdin.next());
		Arrays.sort(list);

		// Print them.
		for (int i=0; i<n; i++)
			System.out.println(list[i]);

		// Now resort student objects using a Comparator instead.
		Arrays.sort(list, new Comparator<student>(){
			public int compare(student a, student b) {
				return b.getName().compareTo(a.getName());
			}
		});

		// Print again.
		System.out.println();
		for (int i=0; i<n; i++)
			System.out.println(list[i]);
	}
}

/*** Same class as in customsort.java ***/
class student implements Comparable<student> {

	private String name;
	private int len;

	public student(String n) {
		name = n;
		len = name.length();
	}

	public String getName() {
		return name;
	}

	public int compareTo(student other) {

		if (this.len != other.len)
			return this.len - other.len;

		return this.name.toLowerCase().compareTo(other.name.toLowerCase());
	}

	public String toString() {
		return name;
	}
}