POJ-Ultra-QuickSort 归并排序求逆序对

这题树状数组加离散化TLE,归并排序却过了。

代码如下:

#include <cstdlib>

#include <cstdio>

#include <cstring>

#include <iostream>

#define MAXN 500005

using namespace std;



int N, a[MAXN], c[MAXN];

long long ans;



void merge_sort(int l, int r)

{

    if (r > l) {

        int mid = (l+r) >> 1;

        merge_sort(l, mid);

        merge_sort(mid+1, r);

        int i, j, k;

        for (i = l, j = mid+1, k = 0;i <= mid && j <= r;) {

            if (a[i] > a[j]) {

                c[k] = a[j];

                ans += (mid-i+1);

                ++j, ++k;

            }

            else {

                c[k] = a[i];

                ++i, ++k;

            }

        }

        for (int h = i; h <= mid; ++h) {

            c[k++] = a[h];

        }

        for (int h = j; h <= r; ++h) {

            c[k++] = a[h];

        }

        for (int i = 0; i <= r-l; ++i) {

            a[l+i] = c[i];

        }

    }

}



int main()

{

    while (scanf("%d", &N), N) {

        ans = 0;

        for (int i = 0; i < N; ++i) {

            scanf("%d", &a[i]);

        }

        merge_sort(0, N-1);

        cout << ans << endl;

    }

    return 0;    

}

你可能感兴趣的:(Quicksort)