You are responsible for cataloguing a sequence of DNA strings (sequences containing only the four letters A, C, G, and T). However, you want to catalog them, not in alphabetical order, but rather in order of "sortedness", from "most sorted" to "least sorted". All the strings are of the same length.
Input
The first line contains two integers: a positive integer n (0 < n ≤ 50) giving the length of the strings; and a positive integer m (1 < m ≤ 100) giving the number of strings. These are followed by m lines, each containing a string of length n.
Output
Output the list of input strings, arranged from "most sorted" to "least sorted". If two or more strings are equally sorted, list them in the same order they are in the input.
Sample Input
10 6
AACATGAAGG
TTTTGGCCAA
TTTGGCCAAA
GATCAGATTT
CCCGGGGGGA
ATCGATGCAT
Sample Output
CCCGGGGGGA
AACATGAAGG
GATCAGATTT
ATCGATGCAT
TTTTGGCCAA
TTTGGCCAAA
Source: East Central North America 1998
my c++ code:
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int measure(string s){
int rev=0;
int len=s.length();
for(int i=0;i<len-1;i++){
for(int j=i+1;j<len;j++){
if(s[i]>s[j]){
rev++;
}
}
}
return rev;
}
int main(){
string s;
getline(cin,s);
istringstream sin(s);
int len,n;
sin>>len>>n;
int *a=new int[n];
string *str=new string[n];
for(int i=0;i<n;i++){
getline(cin,s);
str[i]=s;
a[i]=measure(s);
}
for(int i=0;i<n-1;i++){
int minIndex = i;
for(int j=i+1;j<n;j++){
if(a[j]<a[minIndex]){
minIndex = j;
}
}
swap(a[i],a[minIndex]);
swap(str[i],str[minIndex]);
}
for(int i=0;i<n;i++){
cout<<str[i]<<endl;
}
delete []a;
delete []str;
return 0;
}