代码模板
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 1e5 + 10;
int n;
int a[N], tmp[N];
void merge_sort(int q[], int l, int r)
{
if (l >= r) return;
int mid = l + r >> 1;
merge_sort(q, l, mid);
merge_sort(q, mid + 1, r);
int k = 0, i = l, j = mid + 1;
while (i <= mid && j <= r)
if (q[i] <= q[j]) tmp[k ++ ] = q[i ++ ];
else tmp[k ++ ] = q[j ++ ];
while (i <= mid) tmp[k ++ ] = q[i ++ ];
while (j <= r) tmp[k ++ ] = q[j ++ ];
for (i = l, j = 0; i <= r; i ++, j ++ ) q[i] = tmp[j];
}
int main()
{
cin >> n;
for (int i = 0; i < n; ++ i) cin >> a[i];
merge_sort(a, 0, n - 1);
for (int i = 0; i < n; ++ i) cout << a[i] << " ";
return 0;
}
应用1-求逆序对
原理在于归并排序合并[l,mid]和[mid + 1, r]两个区间时会进行比较,每遇到一对前半段区间小于后半段区间的数就是一组逆序对
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 1e5 + 10;
typedef long long LL;
int n;
int a[N], tmp[N];
LL merge_sort(int a[], int l, int r)
{
if (l >= r) return 0;
int mid = l + r >> 1;
LL res = merge_sort(a, l, mid) + merge_sort(a, mid + 1, r);
int k = 0, i = l, j = mid + 1;
while (i <= mid && j <= r)
{
if (a[i] <= a[j]) tmp[k ++] = a[i ++];
else
{
res += mid - i + 1; // a[i] > a[j],a[k](k > i) 一定 > a[j],所以这里是i及之后关于a[j]的所有逆序对数量 这里采用res++的问题也是当a[i] > a[j]之后,i后面的数据就看不到a[j]了,后面对应的逆序对自然也就找不到了,这里需要全部加上
tmp[k ++] = a[j ++];
}
}
while (i <= mid) tmp[k ++] = a[i ++];
while (j <= r) tmp[k ++] = a[j ++];
for (int i = l, j = 0; j < k; ++ i, ++ j) a[i] = tmp[j];
return res;
}
int main()
{
cin >> n;
for (int i = 0; i < n; ++ i) cin >> a[i];
cout << merge_sort(a, 0, n - 1) << endl;
return 0;
}