1 #include <iostream> 2 #include <cstring> 3 4 using namespace std; 5 const int maxn = 50005; 6 int a[maxn]; 7 int res[maxn]; 8 int ans; 9 10 //归并排序 11 void merge(int l, int r){ 12 //cout<<l<<" "<<r<<endl; 13 int mid = (l + r) >> 1; 14 int i = l, j = mid + 1; 15 int cur = l; 16 while (i <= mid && j <= r){ 17 if (a[i] <= a[j]) 18 res[cur++] = a[i++]; 19 else{ 20 res[cur++] = a[j++]; 21 ans += mid - i + 1; //找到逆序的个数 22 } 23 } 24 while (i <= mid) res[cur++] = a[i++]; 25 while (j <= r) res[cur++] = a[j++]; 26 //排序好后 27 for (int i = l; i <= r; i++) a[i] = res[i]; 28 } 29 void mer_sort(int l, int r){ 30 if (l < r){ 31 int mid = (l + r) >> 1; 32 mer_sort(l, mid); //分解 33 mer_sort(mid + 1, r); //分解 34 merge(l, r); //合并 35 } 36 } 37 int main() 38 { 39 int n; 40 while (cin >> n){ 41 for (int i = 1; i <= n; i++) cin >> a[i]; 42 43 ans = 0; 44 mer_sort(1, n); 45 cout << ans << endl; 46 } 47 return 0; 48 }