hiho 39 二分·归并排序之逆序对

问题

寻找逆序数
http://hihocoder.com/contest/hiho39/problem/1

解法

归并排序,复杂度o(nlogn)

#include 
using namespace std;
enum {maxn = 100000+5};
int a[maxn];
int temp[maxn];
int n;
long long ret;
void mergeSort(int L, int R)
{
    if (L>=R)
        return;
    int m= L+(R-L)/2;
    mergeSort(L, m);
    mergeSort(m+1, R);
    int i = L;
    int j = m+1;
    int k = L;
    int bNum = 0;
    while(i<=m&& j<=R)
    {
        if (a[i] <= a[j])
        {
            temp[k++] = a[i++];
            ret+= bNum;
        }else{
            temp[k++] = a[j++];
            bNum++;
        }
    }
    while(i<=m) {temp[k++] = a[i++]; ret+= bNum;}
    while(j<=R) {temp[k++] = a[j++];}
    memcpy(a+L, temp+L, sizeof(int)*(R+1-L));
    //for (int i = L; i<=R; ++i)
      //  a[i] = temp[i];
}
int main()
{
    scanf("%d", &n);
    for(int i=0; iscanf("%d", a+i);
    ret =0;
    mergeSort(0, n-1);
    printf("%lld\n", ret);
    return 0;
}

你可能感兴趣的:(hiho)