歸併排序求逆序數

畫船聽雨發表於2014-10-31
#include <algorithm>
#include <iostream>
#include <stdlib.h>
#include <string.h>
#include <iomanip>
#include <stdio.h>
#include <string>
#include <queue>
#include <cmath>
#include <stack>
#include <ctime>
#include <map>
#include <set>
#define eps 1e-12
///#define M 1000100
///#define LL __int64
#define LL long long
///#define INF 0x7ffffff
#define INF 0x3f3f3f3f
#define PI 3.1415926535898
#define zero(x) ((fabs(x)<eps)?0:x)

using namespace std;

const int maxn = 30100;

LL a[maxn];
LL temp[maxn];
LL sum;

struct node
{
    LL y1;
    LL y2;
    int id;
}f[maxn];

void Merge(LL a[], int l, int mid, int r)
{
    int begin1 = l;
    int end1 = mid;
    int begin2 = mid+1;
    int end2 = r;
    int k = 0;
    while(begin1 <= end1 && begin2 <= end2)
    {
        if(a[begin1] < a[begin2])
        {
            temp[k++] = a[begin1];
            begin1++;
            sum += begin2-(mid+1);
        }
        else
        {
            temp[k++] = a[begin2];
            begin2++;
        }
    }
    while(begin1 <= end1)
    {
        temp[k++] = a[begin1];
        begin1++;
        sum += end2-mid;
    }
    while(begin2 <= end2)
    {
        temp[k++] = a[begin2];
        begin2++;
    }
    for(int i = l; i <= r; i++) a[i] = temp[i-l];
}

void MergeSort(LL a[], int l, int r)
{
    int mid = (l+r)>>1;
    if(l < r)
    {
        MergeSort(a, l, mid);
        MergeSort(a, mid+1, r);
        Merge(a, l, mid, r);
    }
}

相關文章