#include<iostream>
#include<vector>
#include<algorithm>
#include<string>
#include<iterator>
using namespace std;
class dna{
public:
string s;
int time;
int calcu(){
int n = 0;
int a = s.length();
for(int y = 0;y<a;y++){
for(int x = y+1;x<a;x++){
if(s[y]>s[x])
n++;
}
}
return n;
}
};
bool sm(const dna &v,const dna &u){
if(v.time>u.time)
return false;
else
return true;
}
int main(){
int m,n;
cin >> m;
cin >> n;
dna c[10];
vector<dna> d;
for(int j = 0;j<n;j++){
cin >> c[j].s;
c[j].time = c[j].calcu();
d.push_back(c[j]);
}
sort(d.begin(),d.end(),sm);
vector<dna>::iterator it;
for(it = d.begin();it!=d.end();it++){
cout <<it->s<<endl;
}
}