a538中等合併排序計算逆序對
CPE:Ultra-QuickSort (UVa 10810)
一次算出右半較小元素跨越多少左半元素。
解題思路
若 i<j 而 a[i]>a[j],這對元素就是逆序對。交換相鄰逆序元素恰使逆序對減一;其他相鄰交換不會讓數量下降更多。因此排序最少交換次數等於初始逆序對數,而不是排序時任意交換兩元素的次數。
合併排序先遞迴計算左右兩半的逆序對。合併時,如果右側元素比左側目前元素小,左半尚未取出的全部元素都比它大,一次增加 mid−i;否則取左側,不增加。各層總合併量為 n,且共 log n 層。n=0 結束,最大答案近 n(n−1)/2,必須用 64 位元。
Step-by-step animation
示意:序列 3、1、2
步驟 1 / 3
分割
左半 [3]、右半 [1,2],兩邊各自沒有逆序。
3
1
2
- 內部逆序
- 0
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <algorithm>
#include <numeric>
#include <cmath>
#include <iomanip>
#include <queue>
#include <deque>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <array>
#include <tuple>
#include <functional>
#include <limits>
#include <cstdint>
#include <cctype>
#include <utility>
using namespace std;
long long mergeCount(vector<int> &a, vector<int> &tmp, int l, int r) {
if (r - l <= 1)
return 0;
int mid = (l + r) / 2;
long long ans = mergeCount(a, tmp, l, mid) + mergeCount(a, tmp, mid, r);
int i = l, j = mid, k = l;
while (i < mid && j < r) {
if (a[i] <= a[j])
tmp[k++] = a[i++];
else {
tmp[k++] = a[j++];
ans += mid - i;
}
}
while (i < mid)
tmp[k++] = a[i++];
while (j < r)
tmp[k++] = a[j++];
copy(tmp.begin() + l, tmp.begin() + r, a.begin() + l);
return ans;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
while (cin >> n && n) {
vector<int> a(n), tmp(n);
for (int &x : a)
cin >> x;
cout << mergeCount(a, tmp, 0, n) << '\n';
}
}
先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。