1. 
/**
* FWP, Ausgewählte Probleme aus dem ACM Programming Contest, SS2010
* Problem: 612 - DNA Sorting
* Link: http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&category=8&problem=553&mosmsg=Submission+received+with+ID+7934113
*
* @author Barny Porcio
* @version 1.0, 04/29/2010
*
* Status : Accepted
* Runtime: 1.300
*/


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.StringTokenizer;


public class DNASorting612 {

static int calcinv (String s){
int c = 0;
for (int i = 0; i < s.length(); ++i){
char ch = s.charAt(i);
for (int i2 = i+1;i2 < s.length(); ++i2){
if (s.charAt(i2) < ch)
++c;
}
}
return c;
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
for (int cases = Integer.parseInt(br.readLine()); cases > 0; --cases){
br.readLine();
StringTokenizer st = new StringTokenizer(br.readLine());
st.nextToken();
HashMap<Integer, LinkedList<String>> hm = new HashMap<Integer, LinkedList<String>>();
for (int i = Integer.parseInt(st.nextToken());i > 0; --i){
String s = br.readLine();
int temp = calcinv(s);
if (hm.get(temp) == null){
LinkedList<String> ll = new LinkedList<String>();
ll.add(s);
hm.put(temp, ll);
}
else hm.get(temp).add(s);
}
Object[] arr = hm.keySet().toArray();
Arrays.sort(arr);
for (Object o : arr){
for (String str :hm.get(o))
System.out.println(str);
}
if (cases != 1)
System.out.println();
}
}

}