分治算法
求逆序对数
ultra-quicksort
AC代码:
//用int会出错,改成用long long
#include <iostream>
#include <cstdio>
#include <vector>
#define Max 500005
using namespace std;
long long merge(int input[], int start, int mid, int end) {
vector<int> temp_input;
int m1 = start, m2 = mid+1;
long long count = 0;
while(m1 <= mid && m2 <= end) {
if(input[m1] > input[m2]) {
count += mid-m1+1;
temp_input.push_back(input[m2]);
m2++;
}
else {
temp_input.push_back(input[m1]);
m1++;
}
}
while(m1 <= mid) {
temp_input.push_back(input[m1]);
m1++;
}
while(m2 <= end) {
temp_input.push_back(input[m2]);
m2++;
}
int k = 0;
for(int i=start; i<=end; i++) {
input[i] = temp_input[k++];
}
return count;
}
long long solve(int input[], int start, int end) {
if(start >= end) return 0;
int mid = (start+end)/2;
long long left = solve(input, start, mid);
long long right = solve(input, mid+1, end);
long long left_right = merge(input, start, mid, end);
return left+right+left_right;
}
int main(int argc, const char * argv[]) {
// insert code here...
int n, input[Max];
while(scanf("%d", &n) && n!=0) {
for(int i=0; i<n; i++) {
scanf("%d", &input[i]);
}
long long result = solve(input, 0, n-1);
cout<<result<<endl;
}
return 0;
}