HDU 1394(归并求逆序对)

HDU 1394

原始序列逆序对为ans,新序列的逆序对减少s[i]个,增加n - (s[i] + 1)个,所以增加的逆序对为ans += n - 1 - 2*s[i];

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N  = 5e5+10;
int s[N], b[N], tmp[N];
ll cnt;
inline  void merge_sort(int a[], int l, int r){
    if(l == r) return;
    int mid = (l + r) / 2;
    merge_sort(a, l, mid);
    merge_sort(a, mid + 1, r);
    int i = l, j = mid + 1, k = 0;
    while(i <= mid && j <= r){
        if(a[i] <= a[j]) tmp[k++] = a[i++];
        else tmp[k++] = a[j++], cnt += (ll)mid - i + 1;
    }
    while(i <= mid) tmp[k++] = a[i++];
    while(j <= r) tmp[k++] = a[j++];
    for(i = 0; i < k; i++){
        a[l + i] = tmp[i];
    }
}
int main(){
#ifdef ONLINE_JUDGE
#else
    freopen("in.txt", "r", stdin);
#endif //ONLINE_JUDGE
    int n;
    while(~scanf("%d", &n)){
        cnt = 0;
        for(int i = 1; i <= n; i++){
            scanf("%d", &s[i]);
            b[i] = s[i];
        }
        merge_sort(b, 1, n);
        ll ans = 0x3f3f3f3f;
        for(int i = 1; i <= n; i++){
            cnt += (n - 1 - 2 * s[i]);
            ans = min(cnt, ans);
        }
        printf("%lld\n", ans);
    }
    return 0;
}

 

posted on 2019-03-18 21:34  坤sir  阅读(170)  评论(0编辑  收藏  举报

导航