SPOJ INVCNT

来源:互联网 发布:缤特力 捷波朗 知乎 编辑:程序博客网 时间:2024/06/06 01:30
// http://www.spoj.com/problems/INVCNT/#include <iostream>using namespace std;long long mergeCount(int a[], int low, int mid, int high) {int b[200000];int i = low;int j = mid + 1;int k = low;long long count = 0;while (i <=mid && j <= high) {if (a[i] <= a[j]) {b[k++] = a[i++];} else {b[k++] = a[j++];count += j-k;}}while (i <= mid) {b[k++] = a[i++];}while (j <= high) {b[k++] = a[j++];}for (i = low; i<= high; i++) {a[i] = b[i];}return count;}long long countinversecount(int *a, int low, int high) {if (low < high) {int mid = (low + high) / 2;long long count = 0;count += countinversecount(a, low, mid);count += countinversecount(a, mid + 1, high);count += mergeCount(a, low, mid, high);return count;} else {return 0;}}void f() {int n;cin >> n;int a[n];for (int i = 0; i < n; i++) {cin >> a[i];}long long count = countinversecount(a, 0, n-1);cout << count << endl;}int main() {int t;cin >> t;while (t-- >0) {f();}}

0 0
原创粉丝点击