1007. DNA Sorting

 

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 beexactly 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 ofsortedness', 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 <algorithm>

#include <cstdio>

#include <vector>

#include <string>

using namespace std;

 

int i, n, m, tests;

vector<pair<string,int> > s;

vector<pair<string,int> >::iterator iter;

char stroka[55];

 

int value(string s)

{

  int i, j, res = 0;

  for(i = 0; i < n - 1; i++)

    for(j = i + 1; j < n; j++)

      if (s[i] > s[j]) res++;

  return res;

}

 

int lt(pair<string,int> x, pair<string,int> y)

{

  return (x.second < y.second);

}

 

int main(void)

{

  scanf("%d %d\n",&n,&m);

  for(i = 0; i < m; i++)

  {

    gets(stroka);

    s.push_back(make_pair(stroka,value(stroka)));

  }

 

  stable_sort(s.begin(),s.end(),lt);

 

  for(iter = s.begin();iter != s.end();iter++)

    puts((*iter).first.c_str());

 

  return 0;

}