#include <iostream>#include <algorithm>#include <vector>using namespace std;/* * 歸并求逆序數 * 方法一:求出每個數的逆序對的個數num,對所有num求和后除以2得到逆序數 * 步驟:先求小區間中的每個數的num,再回溯合并兩個小區間為一個大區間并更新大區間中每個數的num */struct Node{ long long int value, num;//num為與value相關的逆序對的個數總和(value前面比它大的數的個數+value后面比它小的數的個數)};void Merge(vector<Node>&a, int s, int e, vector<Node>&temp){ int mid = (s + e) / 2; int i = s, j = mid + 1; int k = s;//k從哪兒開始無所謂,我們這兒從s開始 while (i <= mid&&j <= e) { //將數合并到temp中之前計算這個數的逆序對的個數(更新) if (a[i].value <= a[j].value) a[i].num += j - mid - 1, temp[k++] = a[i++];//[ a[mid+1],a[j-1] ]都小于a[i],個數為j-mid-1個 else a[j].num += mid - i + 1, temp[k++] = a[j++];//[ a[i],a[mid] ]都大于a[j],個數為mid-i+1個 } while (i <= mid) a[i].num += e - mid, temp[k++] = a[i++];//前半部分有剩余時,說明它比后半部分所有數都大,逆序對的個數增加,且都增加e-mid個 for (i = s; i < k; i++)//寫回原容器,為下次更新準備 a[i] = temp[i];}/** 遞歸二分*/void MergeSort(vector<Node>&a, int s, int e, vector<Node>&temp){ if (s < e) { int mid = (s + e) / 2; MergeSort(a, s, mid, temp); MergeSort(a, mid + 1, e, temp); Merge(a, s, e, temp); }}int main(){ int n; while (cin >> n) { vector<Node>a(n); vector<Node>temp(n); for (int i = 0; i < n; i++) cin >> a[i].value, a[i].num = 0; MergeSort(a, 0, n - 1, temp); long long int sum = 0; for (int i = 0; i < n; i++) sum += a[i].num; cout << sum/2 << endl; } return 0;}#include <iostream>#include <algorithm>#include <vector>using namespace std;/* * 歸并求逆序數 * 方法二:求出每個數前面比自己大的數的個數count,累加即為序列的逆序數 */long long int Merge(vector<int>&a, int s, int e, vector<int>&temp){ long long int count = 0; int mid = (s + e) / 2; int i = s, j = mid + 1; int k = s; while (i <= mid&&j <= e) { if (a[i] <= a[j]) temp[k++] = a[i++]; else temp[k++] = a[j++],count+=j-k;//累加 } while (i <= mid) temp[k++] = a[i++]; for (i = s; i < k; i++) a[i] = temp[i]; return count;}/** 遞歸二分*/long long int MergeSort(vector<int>&a, int s, int e, vector<int>&temp){ long long int count = 0; if (s < e) { int mid = (s + e) / 2; count += MergeSort(a, s, mid, temp); count += MergeSort(a, mid + 1, e, temp); count += Merge(a, s, e, temp); } return count;}int main(){ int n; while (cin >> n) { vector<int>a(n); vector<int>temp(n); for (int i = 0; i < n; i++) cin >> a[i]; long long int ans = MergeSort(a, 0, n - 1, temp); cout << ans << endl; } return 0;}