原始序列逆序对为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 ", ans); } return 0; }