DNA Sorting
Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 59510 | Accepted: 23481 |
Description
One measure of ``unsortedness'' in a sequence is the number of pairs of entries that are out of order with respect to each other. For instance, in the letter sequence ``DAABEC'', this measure is 5, since D is greater than four letters to its right and E is greater than one letter to its right. This measure is called the number of inversions in the sequence. The sequence ``AACEDGG'' has only one inversion (E and D)---it is nearly sorted---while the sequence ``ZWQM'' has 6 inversions (it is as unsorted as can be---exactly the reverse of sorted).
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.
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 (0 < 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''. Since two strings can be equally sorted, then output them according to the orginal order.
Sample Input
10 6 AACATGAAGG TTTTGGCCAA TTTGGCCAAA GATCAGATTT CCCGGGGGGA ATCGATGCAT
Sample Output
CCCGGGGGGA AACATGAAGG GATCAGATTT ATCGATGCAT TTTTGGCCAA TTTGGCCAAA//
#include <cstdio>
#include <string>
#include <cstring>
#include <algorithm>
using namespace std;
char ss[110][100];
char back[110][100];
struct Rev
{
int i; //下标
int rev;
};
int comp1(const void *a,const void *b)
{
return (*(Rev *)a).rev > (*(Rev *)b).rev ? 1 : -1;
}
int m,n;
int cnt;
void mergesort(int i,int j,char *str,char *str1)
{
if(j-i>1)
{
int m=(i+j)/2;
mergesort(i,m,str,str1);
mergesort(m,j,str,str1);
int p=i,q=m; int l=i;
while(p<m||q<j)
{
if((p<m&&str[p]<=str[q])||q>=j) str1[l++]=str[p++];
else {str1[l++]=str[q++]; cnt+=m-p;}
}
for(int k=i;k<j;k++)
str[k]=str1[k];
}
}
int main() {
while(scanf("%d%d",&n,&m)==2)
{
Rev r[110];
for(int i=0;i<m;i++)
{
scanf("%s",ss[i]);
memcpy(back[i],ss[i],sizeof(ss[i]));
char str1[50];
cnt=0;
mergesort(0,n,ss[i],str1);
r[i].rev=cnt;
r[i].i=i;
}
qsort(r,m,sizeof(r[0]),comp1);
for(int i=0;i<m;i++)
cout<<back[r[i].i]<<endl;
}
return 0;
}