Inversion
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 131072/131072 K (Java/Others)Total Submission(s): 757 Accepted Submission(s): 321
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
2014 Multi-University Training Contest 5
求逆序数一般有两种方法 数不大的情况下可以用树状数组
数比较大的话 可以树状数组加离散化 或者归并排序
归并排序:
求逆序数一般有两种方法 数不大的情况下可以用树状数组
数比较大的话 可以树状数组加离散化 或者归并排序
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int maxn =1010;
int tree[maxn],n;
int lowbit(int x){
return x&(-x);
}
void update(int x,int y){
while(x<=n){
tree[x]+=y;
x+=lowbit(x);
}
}
int query(int x){
int sum=0;
while(x>0){
sum+=tree[x];
x-=lowbit(x);
}
return sum;
}
int main()
{
while(cin>>n){
memset(tree,0,sizeof(tree));
int a,ans=0;
for(int i=1;i<=n;i++){
cin>>a;
update(a,1);
ans+=i-query(a);
}
cout<<ans<<endl;
}
return 0;
}
归并排序:
#include <iostream>
#include <cstdio>
#define MAX 100001
using namespace std;
int tar[MAX];
int Array[MAX];
long long rs;
void merge(int Array[], int l,int m,int r){
int l1=l,l2=m+1,pp=0;
while(l1<=m&&l2<=r){
if(Array[l1]<=Array[l2]){
tar[pp++]=Array[l1++];
}else{
tar[pp++]=Array[l2++];
rs+=m-l1+1;
}
}
while(l1<=m)tar[pp++]=Array[l1++];
while(l2<=r)tar[pp++]=Array[l2++];
for(int i=l,j=0;i<=r;i++,j++){
Array[i]=tar[j];
}
}
void mergesort(int Array[], int l,int r){
if(l>=r)return;
int m=(l+r)/2;
mergesort(Array, l, m);
mergesort(Array, m+1, r);
merge(Array, l, m, r);
}
long long NiXuShu(int Array[], int n)
{
rs = 0;
mergesort(Array, 0, n-1);
return rs;
}
int main(){
int n,k;
while(~scanf("%d%d",&n,&k)){
for(int i=0;i<n;i++)
scanf("%d",&Array[i]);
long long ans = NiXuShu(Array,n);
if(k>=ans)
printf("0\n");
else
printf("%I64d\n",ans-k);
}
return 0;
}