逆序对的数量(Acwing)
1.首先要想到排序问题中的归并排序来解决此问题;
其次我们要看逆序数的定义是i<j&&a[i]>a[j] ;
下面就来模拟一下;
1 3 2 4 7 8 9 5 6 7
#include<bits/stdc++.h> using namespace std; const int N=1e5+10; typedef long long LL; int tmp[N]; LL merge_sort(int q[], int l, int r) { if (l >= r) return 0; int mid = l + r >> 1; LL res = merge_sort(q, l, mid) + merge_sort(q, mid + 1, r); int k = 0, i = l, j = mid + 1; while (i <= mid && j <= r) if (q[i] <= q[j]) tmp[k ++ ] = q[i ++ ]; else { res += mid - i + 1; tmp[k ++ ] = q[j ++ ]; } while (i <= mid) tmp[k ++ ] = q[i ++ ]; while (j <= r) tmp[k ++ ] = q[j ++ ]; for (i = l, j = 0; i <= r; i ++, j ++ ) q[i] = tmp[j]; return res; } int main(){ int n; cin>>n; int q[N]; for(int i=0;i<n;i++) scanf("%d",&q[i]); cout<<merge_sort(q,0,n-1); return 0; }