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
题解:
用归并排序求出逆序数,题意是只能交换k次相邻的数,所以答案为cnt-k,但是不能为负数,所以答案为max(cnt-k,0)
代码:
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
typedef long long LL;
const LL maxn = 1e5+10;
LL cnt;
void merge_sort(LL A[],int x,int y,LL T[])
{
if(y-x>1)
{
int m = x+(y-x)/2; //划分
int p=x,q=m,i=x;
merge_sort(A,x,m,T);
merge_sort(A,m,y,T);
while(p<m||q<y)
{
if(q>=y||(p<m&&A[p]<=A[q]))
T[i++]=A[p++];
else
{T[i++]=A[q++];cnt+=m-p;}
}
for(i=x;i<y;i++) A[i]=T[i];
}
}
int main()
{
LL n,k;
LL A[maxn];
LL T[maxn];
while(cin>>n>>k)
{
memset(T,0,sizeof(T));
memset(A,0,sizeof(A));
cnt=0;
for(int i=0;i<n;i++)
cin>>A[i];
merge_sort(A,0,n,T);
cout<<max(cnt-k,(LL)0)<<endl;
}
return 0;
}