inversions

 

描述

bobo has a sequence a 1,a 2,…,a n. He is allowed to swap two adjacent(相邻) numbers for no more than k times. Find the minimum number of inversions after his swaps. Note: The number of inversions is the number of pair (i,j) where 1≤ia j.

输入

The input consists of several tests. For each tests: The first line contains 2 integers n,k (1≤n≤10 5,0≤k≤10 9). The second line contains n integers a 1,a 2,…,a n (0≤a i≤10 9).

输出

For each tests: A single integer denotes the minimum number of inversions.

样例输入
3 0
3 2 1
样例输出
3

思路 

此题是一道求逆序对数量的题目,我们利用归并排序

#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
#include<vector>
typedef long long ll;
const int N = 1e5+5;
using namespace std;
ll q[N], tmp[N],ans;
void count_invertion(ll l,ll r) {//求逆序对数量
//归并排序模版
    if (l >= r) return;
	ll t=0;
	ll mid = l + (r - l) / 2;
	count_invertion(l, mid);
	count_invertion(mid + 1, r);
	ll i = l, j = mid + 1;
	while (i <=mid && j <= r) {
		if (q[i] > q[j]) {//存在逆序
			ans += mid - i + 1;
			tmp[t++] = q[j++];
		}
		else tmp[t++] = q[i++];
	}
	
	while (i <= mid) tmp[t++] = q[i++];
	while (j <= r) tmp[t++] = q[j++];
	for (int i = l, j = 0; i <= r; i++,j++) q[i] = tmp[j];
}
int main()
{
	ll n, k;
	while (cin >> n >> k)
	{
		for (int i = 0; i < n; i++) scanf("%d", &q[i]);
		ans=0;
		count_invertion(0,n-1);
		if (ans <= k) cout << 0 << endl;
     // 当ans小于等于k,在k次变换内数组q就会变得有序
		else cout << ans - k << endl;
	}
}

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值