import java.io.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;

public class Main implements Runnable{
    static int n = 0;
    public class DNA implements Comparable<DNA>{
        String code;
        int invnum;
        DNA(String s){
            code = s;
            int sum = 0;
            for(int i = 0; i < n-1;i++){
                for(int j = i+1; j < n; j++){
                    if(s.charAt(i) > s.charAt(j)) sum++;
                }
            }
            invnum = sum;
        }
        public int compareTo(DNA d){
            if(invnum > d.invnum) return 1;
            if(invnum < d.invnum) return -1;
            return 0;
        }

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


    public void run(){
                try{
                    Scanner s = new Scanner(new File("sorting.in"));
                    PrintWriter p = new PrintWriter(new File("soting.out"));
                    n = s.nextInt();
                    int m = s.nextInt();
                    s.nextLine();
                    DNA[] frag = new DNA[m];

                    for(int i = 0; i < m; i++){
                        frag[i] = new DNA(s.nextLine());
                    }
                    Arrays.sort(frag);
                    for(int i = 0; i < m; i++){
                        p.println(frag[i].code);
                    }
                    p.close();

                } catch(Exception e){
                    e.printStackTrace();
                    System.exit(1);
                }
    }

}