用c++语言写以下程序:求逆序对的数目
时间: 2023-09-08 09:09:51 浏览: 93
以下是使用归并排序求逆序对数目的 C++ 代码:
```c++
#include <iostream>
using namespace std;
long long merge(int arr[], int temp[], int left, int mid, int right) {
long long count = 0;
int i = left, j = mid, k = left;
while (i <= mid - 1 && j <= right) {
if (arr[i] <= arr[j])
temp[k++] = arr[i++];
else {
temp[k++] = arr[j++];
count += mid - i;
}
}
while (i <= mid - 1)
temp[k++] = arr[i++];
while (j <= right)
temp[k++] = arr[j++];
for (i = left; i <= right; i++)
arr[i] = temp[i];
return count;
}
long long mergeSort(int arr[], int temp[], int left, int right) {
long long count = 0;
if (left < right) {
int mid = (left + right) / 2;
count += mergeSort(arr, temp, left, mid);
count += mergeSort(arr, temp, mid + 1, right);
count += merge(arr, temp, left, mid + 1, right);
}
return count;
}
long long countInversions(int arr[], int n) {
int temp[n];
return mergeSort(arr, temp, 0, n - 1);
}
int main() {
int n;
cout << "Enter the number of elements: ";
cin >> n;
int arr[n];
cout << "Enter the elements: ";
for (int i = 0; i < n; i++)
cin >> arr[i];
long long inversions = countInversions(arr, n);
cout << "Number of inversions: " << inversions << endl;
return 0;
}
```
输入格式为:第一行输入元素个数 n,第二行输入 n 个元素。输出逆序对的数目。
阅读全文