POJ 1007 DNA Sorting

#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>

using namespace std;

const int MAXN = 110;

struct DNA_Node
{
    int num;
    char str[MAXN];

    DNA_Node()
    {
        num = 0;
        memset(str, 0, sizeof(str));
    }
}DNA_Arr[MAXN];

int sum;
char b[MAXN], a[MAXN];

int cmp(const void* a, const void* b)
{
    DNA_Node* aa = (DNA_Node *)a;
    DNA_Node* bb = (DNA_Node *)b;
    return aa->num - bb->num;
}

void Merge_Find_InverseNum(int low, int mid, int high)
{
    int i = low, j = mid+1, k = low;
    while(i <= mid && j <= high)
    {
        if(a[i] <= a[j])
            b[k++] = a[i++];
        else
            b[k++] = a[j++], sum += (mid - i + 1);
    }

    while(i <= mid)
        b[k++] = a[i++];
    while(j <= high)
        b[k++] = a[j++];

    for(i = low; i <= high; ++i)
        a[i] = b[i];
    return ;
}

void Merge_Sort(int low, int high)
{
    if(low == high)
        return ;
    if(low < high)
    {
        int mid = (low + high) >> 1;
        Merge_Sort(low, mid);
        Merge_Sort(mid+1, high);
        Merge_Find_InverseNum(low, mid, high);
    }
}

int main()
{
    int len, num;
    while(~scanf("%d %d", &len, &num))
    {
        for(int i = 0; i < num; ++i)
        {
            cin>>DNA_Arr[i].str;
            strcpy(a, DNA_Arr[i].str);
            sum = 0;
            Merge_Sort(0, len-1);
            DNA_Arr[i].num = sum;
        }

        qsort(DNA_Arr, num, sizeof(DNA_Arr[0]), cmp);
        for(int i = 0; i < num; ++i)
            cout<<DNA_Arr[i].str<<endl;
    }
    return 0;
}

你可能感兴趣的:(归并排序,逆序数)