#include <iostream>#include<stdio.h>#include <map>using namespace std;int reverseCount(string s){ int num = 0; string::iterator lit = s.begin(); string::iterator rit; for(; lit < s.end(); lit++) for(rit = lit + 1; rit <s.end(); rit++) { if(*lit > *rit) { num++; } } return num;}int main(){ int loop; long n,m; string s; map<long, string> matrix; cin >> loop; while(loop--) { matrix.clear(); cin >> n >> m; for(int i=0;i<m;i++) { cin >> s; matrix.insert(pair<long, string>(reverseCount(s)*m+i, s)); } map<long, string>::iterator it = matrix.begin(); for(; it != matrix.end(); it++) { cout << it->second << endl; } if(loop) { cout << endl; } } return 0;}