题目链接:http://acm.hust.edu.cn/vjudge/contest/view.action?cid=86640#problem/A
题目:
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对相邻的数,求序列的逆序数。
分析:
直接求出原序列中的逆序数,用逆序数减去交换的次数k即可。
注意当最终值小于0时将其换成0。
1 #include<iostream> 2 using namespace std; 3 const int maxn=100005; 4 long long a[maxn],t[maxn]; 5 long long count; 6 void slove( long long*A,int x,int y, long long*T) 7 { 8 if(y-x>1) 9 { 10 int m=x+(y-x)/2; 11 int p=x,q=m,i=x; 12 slove(A,x,m,T); 13 slove(A,m,y,T); 14 while(p<m||q<y) 15 if(q>=y||(p<m&&A[p]<=A[q])) 16 T[i++]=A[p++]; 17 else { 18 T[i++]=A[q++]; 19 count+=m-p; 20 } 21 for(i=x;i<y;i++) A[i]=T[i]; 22 } 23 } 24 int main() 25 { 26 int n; 27 long long k; 28 while(cin>>n>>k) 29 { 30 count=0; 31 for(int i=0;i<n;i++) 32 cin>>a[i]; 33 slove(a,0,n,t); 34 if(k<count) 35 cout<<count-k<<endl; 36 else cout<<'0'<<endl; 37 } 38 return 0; 39 }