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
题意:给一个序列和交换次数k,求交换后序列最小的的逆序数....
解题思路:先求出原始序列的逆序数,然后再减去交换次数,就是答案...值得注意的是,如果交换次数减原始逆序数小于0则,答案为0...
求逆序数,这里用到了归并排序..
代码如下:0
1 #include <stdio.h> 2 #include <string.h> 3 int n,k,A[100000],T[100000]; 4 long long ans; 5 void guibing(int* A,int x,int y,int* T) 6 { 7 if(y-x>1){ 8 int m=x+(y-x)/2; 9 int p=x,q=m,i=x; 10 guibing(A,x,m,T); 11 guibing(A,m,y,T); 12 while(p<m||q<y){ 13 if(q>=y||(p<m&&A[p]<=A[q])) T[i++]=A[p++]; 14 else { 15 T[i++]=A[q++]; 16 ans+=m-p; 17 } 18 } 19 for(i=x;i<y;i++) A[i]=T[i]; 20 } 21 } 22 int main() 23 { 24 while(scanf("%d%d",&n,&k)==2&&n){ 25 ans=0; 26 for(int i=0;i<n;i++){ 27 scanf("%d",&A[i]); 28 } 29 memset(T,0,sizeof(T)); 30 guibing(A,0,n,T); 31 if(ans-k<0) 32 ans=0; 33 else 34 ans=ans-k; 35 printf("%I64d ",ans); 36 } 37 return 0; 38 }