POJ 1007 逆序数+排序

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

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

题目大意: 给出m个字符串以及字符串的长度n, 对m个字符串按照逆序数从小到大的顺序进行排序。 每个字符串都只含有A、C、G、T四种字母。

思路: 在序列a1……ai……aj……an中, 若i<j, 且ai>aj, 那么这对数就称之为一个逆序对。 因为字符串只有A、C、G、T四种字母, 因此对字符串从后向前遍历, 记录A、C、G、 T的数量就可以计算出逆序对了。 设其数量分别为na,nc,ng,nt,到遇C时, cnt+=na; 遇到G时, cnt+=na+nc;遇到T时, cnt+=na+nc+ng。 用结构体存储字符串和逆序对数, 最后用sort排序就行了。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
using namespace std;

struct node
{
    char s[55];
    int num;
};

bool cmp(node a,node b)
{
    return a.num<b.num;//按照逆序对数从小到大排序
}

node a[105];

int main()
{
    int n,m;
    scanf("%d %d",&n,&m);
    for(int i=0;i<m;i++)
    {
        scanf("%s",a[i].s);
        int len=n;
        int na=0,nc=0,ng=0,nt=0;
        int cnt=0;
        for(int j=len-1;j>=0;j--)
        {
            if(a[i].s[j]=='A')
                ++na;
            else if(a[i].s[j]=='C')
            {
                cnt+=na;
                ++nc;
            }
            else if(a[i].s[j]=='G')
            {
                cnt+=na+nc;
                ++ng;
            }
            else
            {
                cnt+=na+nc+ng;
                ++nt;
            }
        }
        a[i].num=cnt;
    }
    sort(a,a+m,cmp);
    for(int i=0;i<m;i++)
        printf("%s\n",a[i].s);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/xiji333/article/details/88323683