如2 4 3 1中,2 1,4 3,4 1,3 1是逆序,逆序数是4。给出一个整数序列,求该序列的逆序数。
标签:cin str 输入 amp temp 归并 lse cpp for
4
2 4 3 1
4
实际上是归并排序, 顺便求一下逆序数
#include <iostream> using namespace std; long long int a[50010], b[50010], temp[50010]; int cnt; void Merge(int left, int mid, int right) { int i = left, j = mid + 1, k = left; while(i <= mid && j <= right) { if(a[i] > a[j]) { temp[k ++] = a[j ++]; cnt = cnt + mid - i + 1; } else { temp[k ++] = a[i ++]; } } while(i <= mid) { temp[k ++] = a[i ++]; } while(j <= right) { temp[k ++] = a[j ++]; } for(i = left; i <= right; ++ i) { a[i] = temp[i]; } } void mergeSort(int left, int right) { if(left < right) { int mid = left + (right - left) / 2; mergeSort(left, mid); mergeSort(mid + 1, right); Merge(left, mid, right); } } int main() { int n, m; cin >> n; for(int i = 1; i <= n; ++ i) cin >> a[i]; mergeSort(1, n); // for(int i = 1; i <= n; ++ i) // cout << a[i] << " "; // cout << endl; cout << cnt << endl; return 0; }
标签:cin str 输入 amp temp 归并 lse cpp for
原文地址:https://www.cnblogs.com/mjn1/p/10593150.html