Description
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 a i>a j.
Input
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).
Output
A single integer denotes the minimum number of inversions.
Sample Input
Sample Output
#include<cstdio>
#include<cstring>
#include<algorithm>
int A[500004],T[500004];
long long cnt;
using namespace std;
void init(int n)
{
for(int i=0;i<n;i++)
scanf("%d",&A[i]);
}
void merge_sort(int *A,int x,int y,int *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()
{
int n,k;
while(scanf("%d%d",&n,&k)!=EOF)
{
init(n);
cnt=0;
memset(T,0,sizeof(T));
merge_sort(A,0,n,T);//不能把n寫成n-1,否則會答案錯誤
if(cnt-k>=0)
cnt=cnt-k;
else
cnt=0;
printf("%I64d\n",cnt);
}
return 0;
}