倘若q[i]>q[j],那么在左半边区间i右边的数都大于q[j]
故S[j]=mid-i+1
#includeusing namespace std; const int N = 100010; int n, m; int q[N], tmp[N]; long long merge_sort(int q[], int l, int r) { if (l >= r) { return 0; //TODO } int mid = (l + r) / 2; long long ans = merge_sort(q, l, mid) + merge_sort(q, mid + 1, r); //递归函数遇到return返回结果 int k = 0, i = l, j = mid + 1; while (i <= mid && j <= r) { if (q[i] <= q[j]) { // 这里是小于等于 tmp[k++] = q[i++]; } else { // 注意:只有当q[i]>q[j]才记录逆序对,相等时不计算 ans += mid - i + 1; tmp[k++] = q[j++]; } } while (i <= mid) { tmp[k++] = q[i++]; } while (j <= r) { tmp[k++] = q[j++]; } for (int i = l, j = 0; i <= r; i++, j++) { // q[]数组 i的起始位置是l q[i] = tmp[j]; //TODO } return ans; } int main() { cin >> n; for (int i = 0; i < n; i++) { cin >> q[i]; } long long num = merge_sort(q, 0, n - 1); cout << num << endl; return 0; }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)