欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

归并排序求逆序对

程序员文章站 2022-05-10 11:52:59
...

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 sequenceDAABEC’’, 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 sequenceZWQM’’ 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'', frommost 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 frommost 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 <iostream>
#include <stdio.h>
#include <algorithm>
using namespace std;
int n, m;

struct node{
    char s[50];
    int unsorted_num;
}DNA[110];
bool cmp(node a,node b)
{
    if(a.unsorted_num<b.unsorted_num)
        return true;
    else
        return false;
}
int unsort(char s[])
{
    int cnt[4]={0},unsorted_N=0;
    for(int i=0;i<n;i++)
    {
        switch(s[i])
        {
            case 'A':
            {
                cnt[0]++;
                unsorted_N=unsorted_N+cnt[1]+cnt[2]+cnt[3];
                break;
            }
            case 'C':
            {
                cnt[1]++;
                unsorted_N=unsorted_N+cnt[2]+cnt[3];
                break;
            }
            case 'G':
            {
                cnt[2]++;
                unsorted_N=unsorted_N+cnt[3];
                break;
            }
            case 'T':
            {
                cnt[3]++;
                break;
            }
        }
    }
    return unsorted_N;
}
int main()
{
    scanf("%d %d",&n,&m);
    for(int i=0;i<m;i++)
    {
       scanf("%s",DNA[i].s);
       DNA[i].unsorted_num=unsort(DNA[i].s);
    }
    sort(DNA,DNA+m,cmp);
    for(int i=0;i<m;i++)
    {
        printf("%s\n",DNA[i].s);
    }
    return 0;
}