[算法]POJ-ACM DNA Sorting

http://poj.org/problem?id=1007

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. 

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
这道题目并不是说很难,但是在这道题目中,我感觉到了STL的强大,为了解决这个问题,我写了一个求逆序数的函数,其他的基本是利用了STL中的algorithm vector,string,很是方便,近来做ACM越发感觉STL的强大,但是有一点不足的是可能是在运行效率、内存利用方面,因为在看到与其他的比较,觉得其他人的运行时间在毫秒级以下,我的就在毫秒级,至于内存占用量有时候比有些人稍多些,也比有些人的稍少些,但是不是最优,可能是我水平还没够吧。的加油
#include <iostream>

#include <vector>

#include <string>

#include <algorithm>

using namespace std;

unsigned int NumberOfInversion(const string& str)

{

    unsigned int n = 0;

    string::const_iterator it = str.begin(),next;

    while (str.end() != it)

    {

        next = it+1;

        while (str.end() != next)

        {

            if (*it > * next)

            {

                ++n;

            }

            ++next;

        }

        ++it;

    }

    return n;

}

bool compare(const string& str1, const string& str2)

{

    if(NumberOfInversion(str1) < NumberOfInversion(str2))

    {

        return true;

    }

    return false;

}



void myPrint (const string& str) {

    cout <<str<<endl;

}



int main()

{

    unsigned int row,col;

    cin>>col>>row;

    string str;

    vector<string> vec;

    while (row--)

    {

        cin>>str;

        vec.push_back(str);

    }

    sort(vec.begin(),vec.end(),compare);

    for_each(vec.begin(),vec.end(),myPrint);

    return 0;

} 

 


本文基于知识共享署名-非商业性使用 3.0 许可协议进行许可。欢迎转载、演绎,但是必须保留本文的署名林羽飞扬,若需咨询,请给我发信

你可能感兴趣的:(sort)