close

https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=1751

 

#include<bits/stdc++.h>

using namespace std;

int temp[500000];

 

long long int mergesort(int a[], int x, int y, long long int k) {

    if (y == x)

        return k;

    k = mergesort(a, x, (x+y)/2, k);

    k = mergesort(a, (x+y)/2+1, y, k);

 

    for (int i = x, i1 = (x+y)/2+1, j = (x+y)/2, j1 = y, l = 0;;) {

        if (i>j && i1>j1)

            break;

        else {

            if (i>j) {

                while (i1 <= j1) temp[l] = a[i1], i1++, l++;

            }

            else if (i1>j1) {

                while (i<=j) temp[l] = a[i], i++, l++;

            }

            else if (a[i] > a[i1]) {

                temp[l] = a[i1], k+= (j-i+1), l++, i1++;

            }

            else if (a[i] < a[i1]) {

                temp[l] = a[i], l++, i++;

            }

        }

    }

    for(int i = x, j = 0; i<=y; i++, j++)

        a[i] = temp[j];

    return k;

}

int main() {

    int n, a[500000];

    long long int k;

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

        k = 0;

        for(int i = 0; i<n; i++)

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

        k = mergesort(a, 0, n-1, k);

        printf("%lld\n", k);

    }

    return 0;

}

arrow
arrow
    文章標籤
    UVA10810 Ultra-QuickSort
    全站熱搜

    楓綺 發表在 痞客邦 留言(0) 人氣()