HDU 4911. 归并排序求逆序对数目
原题链接
简单
作者:
史一帆
,
2021-04-11 09:48:54
,
所有人可见
,
阅读 190
思路:先求出所有的逆序对数目。如果小于k,说明所有的逆序对都可以被交换消去,输出0;否则只能消去k个,输出 逆序对数-k。求逆序对用归并排序。
#include <iostream>
using namespace std;
const int N = 100010;
typedef long long LL;
int n, k;
int q[N], tmp[N];
LL merge_sort(int q[], int l, int r)
{
if (l >= r) return 0;
int mid = l + r >> 1;
LL res = merge_sort(q, l, mid) + merge_sort(q, mid + 1, r);
int i = l, j = mid + 1, k = 0;
while (i <= mid && j <= r)
{
if (q[i] <= q[j]) tmp[k ++] = q[i ++];
else
{
tmp[k ++] = q[j ++];
res += mid - i + 1;
}
}
while (i <= mid) tmp[k ++] = q[i ++];
while (j <= r) tmp[k ++] = q[j ++];
for (int i = l, j = 0; i <= r; i ++, j ++) q[i] = tmp[j];
return res;
}
int main()
{
while (cin >> n >> k)
{
for (int i = 0; i < n; i ++) cin >> q[i];
LL cnt = merge_sort(q, 0, n - 1);
if (cnt <= k) cout << "0" << endl;
else cout << cnt - k << endl;
}
return 0;
}