对应HDU题目:点击打开链接
Description
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≤i<j≤n and a i>a j.
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 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).
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
For each tests:
A single integer denotes the minimum number of inversions.
A single integer denotes the minimum number of inversions.
Sample Input
3 1 2 2 1 3 0 2 2 1
Sample Output
1 2
因为是相邻元素互换,故每换一次都会减少一对逆序数。所以直接愉快地套汝佳哥归并排序部分代码求出逆序数cnt,
如果cnt-k<0,则肯定能把原序列换成递增,即没有逆序数,否则输出cnt-k。
#include <iostream>
#include <cstring>
#include <algorithm>
#include <cstdio>
using namespace std;
#define LL long long
int shu[100005],vis[100005];
LL cnt=0;
void mer(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;
mer(A,x,m,t);
mer(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){
for(int i=1;i<=n;i++){
scanf("%d",&shu[i]);
}
cnt=0;
mer(shu,1,n+1,vis);
if(cnt-k<0) printf("%d\n",0);
else printf("%I64d\n",cnt-k);
}
}