题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4911
Inversion
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 131072/131072 K (Java/Others)Total Submission(s): 304 Accepted Submission(s): 133
Problem 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
Author
Xiaoxu Guo (ftiasch)
Source
Recommend
这一道是签到题。因为每次操作都会使逆序数减少。只需要用归并排序算出逆序数,然后判断它与k的大小即可。
#include<iostream>
#include<cstring>
#include<cmath>
#include<cstdio>
#include<algorithm>
#include<cstdlib>
#include<map>
#include<set>
#include<vector>
#include<string>
#include<stack>
#include<queue>
#include<bitset>
using namespace std;
#define CLR(A) memset(A,0,sizeof(A))
typedef long long ll;
const int MAX=500000;
int L[MAX],R[MAX],a[MAX];
void merge(int *a,int p,int mid ,int q,ll &cnt){
int i,j;
for(i=p;i<=mid;i++) L[i]=a[i];
for(j=mid+1;j<=q;j++) R[j]=a[j];
i=p;j=mid+1;
int w=p;
while(i<=mid&&j<=q){
if(L[i]<=R[j]) a[w++]=L[i++];
else{
cnt+=mid-i+1;
a[w++]=R[j++];
}
}
while(i<=mid) a[w++]=L[i++];
while(j<=q) a[w++]=R[j++];
}
void mergeSort(int *a,int p,int q,ll &cnt){
if(p<q){
int mid=(p+q)>>1;
mergeSort(a,p,mid,cnt);
mergeSort(a,mid+1,q,cnt);
merge(a,p,mid,q,cnt);
}
}
int main(){
int n,k;
while(~scanf("%d%d",&n,&k)){
ll cnt=0;
for(int i=0;i<n;i++) scanf("%d",&a[i]);
mergeSort(a,0,n-1,cnt);
cnt=cnt<=k?0:cnt-k;
printf("%I64d\n",cnt);
}
return 0;
}