解题思路:
如果原序列的逆序对数大于交换次数,那么最少的逆序对数量就是原序列逆序对-交换次数。
如果原序列的逆序对数小于等于交换次数,那么最少的逆序对数量为0,因为交换次数超过逆序对数,可以把这些逆序对全部消除。
代码如下:
#include <iostream>
using namespace std;const int N = 100010;
typedef long long LL;
LL cnt = 0;
LL a[N];
LL w[N];
int n, p;
void merge_sort(int l, int r) {if (l >= r)return ;int mid = (l + r) >> 1;merge_sort(l, mid);merge_sort(mid + 1, r);int k = 0, i = l, j = mid + 1;while (i <= mid && j <= r) {if (a[i] <= a[j])w[k++] = a[i++];else {cnt += mid - i + 1;w[k++] = a[j++];}}while (i <= mid)w[k++] = a[i++];while (j <= r)w[k++] = a[j++];for (int i = l, j = 0; i <= r; i++, j++)a[i] = w[j];
}int main() {while (cin >> n >> p) {cnt = 0;for (int i = 0; i < n; i++)cin >> a[i];merge_sort(0, n - 1);if (cnt <= p)cout << "0" << endl;elsecout << cnt - p << endl;}return 0;
}