Problem Description
bobo has a sequence a1,a2,…,an. 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≤i<j≤n and ai>aj.
Input
The input consists of several tests. For each tests:
The first line contains 2 integers n,k (1≤n≤105,0≤k≤109). The second line contains n integers a1,a2,…,an (0≤ai≤109).
Output
For each tests:
A single integer denotes the minimum number of inversions.
分析:注意此题的交换只能在相邻元素间进行,并不能任意交换!!!
因此想到了归并排序,因为归并排序的基础为交换元素,可视为一种加强版的选择排序(都通过交换元素进行)
因此在归并排序中左边序列大于右边序列时就会出现逆序对,查找左序列中在a[i]右侧的数据个数即为逆序数
但因为可以交换k次,每交换一次就减少一个逆序数,即当cnt>k时,结果为cnt-k 小于等于时说明cnt为0(全都交换完了)
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll maxn=100005;
ll a[maxn],b[maxn],cnt;
void Merge(ll l,ll mid,ll r)//合并
{
ll i=l,j=mid+1,t=0;
while(i<=mid&&j<=r)
{
if(a[i]>a[j])
{
b[t++]=a[j++];
cnt+=mid-i+1;
}
else
{
b[t++]=a[i++];
}
}
while(i<=mid) b[t++]=a[i++];
while(j<=r) b[t++]=a[j++];
for(i=0;i<t;i++) a[l+i]=b[i];
}
void Mergesort(ll l,ll r)
{
if(l<r)
{
ll mid=(l+r)/2;
Mergesort(l,mid);
Mergesort(mid+1,r);
Merge(l,mid,r);
}
}
int main()
{
ll n,k;
while(cin>>n>>k)
{
cnt=0;
for(ll i=0;i<n;i++)
{
cin>>a[i];
}
Mergesort(0,n-1);
if(cnt<=k) cout<<0<<endl;
else cout<<cnt-k<<endl;
}
return 0;
}