经典问题,归并排序,求逆序数。
代码如下:
#include <iostream> #include <cstdlib> #include <cstring> #include <iomanip> #include <cstdio> #include <cmath> using namespace std; long long a[500002], b[500002], cct; void merge_sort(int x, int y) { if(y - x > 1) { int m = x + (y - x) / 2; int xx = x, yy = m, i = x; merge_sort(x, m); merge_sort(m, y); while(xx < m || yy < y) { if(yy >= y || (xx < m && a[xx] <= a[yy])) b[i++] = a[xx++]; else { b[i++] = a[yy++]; cct += m - xx; } } for(int i = x; i < y; i++) a[i] = b[i]; } } int main() { #ifdef test freopen("in.txt", "r", stdin); #endif int num; while(scanf("%d", &num), num) { for(int i = 0; i < num; i++) scanf("%I64d", &a[i]); cct = 0; merge_sort(0, num); printf("%I64d\n", cct); } return 0; }