思路:
归并排序然后减去K
CODE
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define NN 500004
#define NL 1000
long long res;
int b[NN]; // 中间辅助数组
int ls[NN];
void copy(int l, int r)
{
int i;
for(i = l; i <= r; i++)
ls[i] = b[i];
}
void merge(int l, int mid ,int r)
{
int i = l;
int j = mid+1;
int k = l;
while(i <= mid && j <= r)
{
if(ls[i] <=ls[j])
{
b[k++] = ls[i];
i++;
}
else
{
b[k++] = ls[j];
j++;
res += mid-i+1;
}
}
while(i <= mid)
{
b[k++] = ls[i];
i++;
}
while(j <= r)
{
b[k++] = ls[j];
j++;
}
}
void mergesort(int l, int r)
{
if(l < r)
{
int mid = l+(r-l)/2;
mergesort(l,mid);
mergesort(mid+1,r);
merge(l,mid,r);
copy(l,r);
}
}
int main()
{
int n, k;
while(~scanf("%d%d",&n,&k))
{
int i;
res = 0;
for(i = 1; i <= n; i++)
scanf("%d",&ls[i]);
mergesort(1,n);
res = res - k;
if(res < 0)
res = 0;
printf("%lld\n",res);
}
return 0;
}