归并排序求逆元;
#include <cstdio> #define MAXN 5000+10 #define LL long long #include <iostream> using namespace std; int a[MAXN], tmp[MAXN]; int b[MAXN]; LL ans; void Merge(int l, int m, int r) { int i=l; int j=m+1; int k=l; while(i<=m && j<=r) { if(a[i]> a[j]) { tmp[k++]=a[j++]; ans+=m-i+1; } else { tmp[k++]=a[i++]; } } while(i<=m) tmp[k++]=a[i++]; while(j<=r) tmp[k++]=a[j++]; for(int i=l; i<=r; i++) { a[i]=tmp[i]; } } void Merge_sort(int l, int r) { if(l <r) { int m=(l+r)>> 1; Merge_sort(l, m); Merge_sort(m+1, r); Merge(l, m, r); } } int main() { int n; LL res; while(scanf("%d", &n) != EOF) { for(int i=0; i<n; i++) { scanf("%d", &a[i]); b[i]=a[i]; } ans =0; Merge_sort(0, n-1); res=ans; for(int i=0; i<n; i++) { res += n-1-b[i]-b[i]; ans= min(ans, res); } printf("%lld\n", ans); } return 0; }
时间: 2024-10-27 13:22:29