题目链接:POJ 1804 Brainman
题目大意:
题解:
在归并排序的过程中记录逆序对个数。
#include <algorithm>
#include <iostream>
using namespace std;
int ans, s[1005], t[1005], n, T;
void merge(int l, int r) {
int p, q, mid, len;
if (l == r) return;
mid = l + r >> 1;
merge(l, mid);
merge(mid + 1, r);
p = l;
q = mid + 1;
len = r - l + 1;
for (int i = 0; i < len; ++i) {
if ((q > r) || (s[p] <= s[q] && p <= mid)) {
t[l + i] = s[p++];
} else {
t[l + i] = s[q++];
ans += mid - p + 1;
}
}
for (int i = l; i <= r; ++i) {
s[i] = t[i];
}
}
int main() {
cin >> T;
for (int t = 1; t <= T; ++t) {
cin >> n;
for (int i = 1; i <= n; ++i) {
cin >> s[i];
}
ans = 0;
merge(1, n);
cout << "Scenario #" << t << ":" << endl << ans << endl << endl;
}
return 0;
}