Problem Description
bobo has a sequence a1,a2,…,an. 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 ai>aj.
Input
The input consists of several tests. For each tests:
The first line contains 2 integers n,k (1≤n≤105,0≤k≤109). The second line contains n integers a1,a2,…,an (0≤ai≤109).
Output
For each tests:
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
思路:归并排序求逆序数。
把原数组化成每个长度为1的小块,然后再合并,再合并中,每次当后面的数小于前面的数时,逆序数(cnt+=mid-i+1),因为每个数组自生有序,所以是从中间开始寻找逆序数的个数。
#include<iostream>
using namespace std;
typedef long long ll;
const int maxn = 100007;
ll a[maxn], b[maxn];//临时存放变量
ll cnt = 0;
void Merge(ll l,ll mid,ll r)
{
int i = l, j = mid + 1, t = 0;//t是b数组的下标
while(i<=mid&&j<=r)
{
if(a[i]>a[j])
b[t++] = a[j++], cnt += mid - i + 1;//计算逆序数
else
b[t++] = a[i++];
}
while(i<=mid) b[t++] = a[i++];
while(j<=r) b[t++] = a[j++];
for (int i = 0;i<t;i++)
a[l + i] = b[i];//把b[]中的值复制给a[]
}
void Mergesort(ll l,ll r)
{
if(l<r)
{
ll mid = (l + r) >> 1;
Mergesort(l, mid);
Mergesort(mid+1, r);
Merge(l,mid,r);
}
}
int main()
{
freopen("11.txt", "r", stdin);
ll n, k;
while(scanf("%lld%lld",&n,&k)!=EOF)
{
cnt = 0;
for (int i = 0;i<n;i++)
scanf("%lld", &a[i]);
Mergesort(0, n-1);
if(cnt<=k)
printf("0\n");
else
printf("%lld\n", cnt - k);
}
return 0;
}
归并排序代码:
#include<iostream>
using namespace std;
//归并排序
typedef long long ll;
const int maxn = 10000;
ll a[maxn], b[maxn];
void Merge(ll l,ll mid,ll r)
{
ll i = l, j = mid + 1, t = 0;
while(i<=mid&&j<=r)
{
if(a[i]>a[j])
b[t++] = a[j++];
else
b[t++] = a[i++];
//cnt += mid - i + 1;
}
while(i<=mid) b[t++] = a[i++];
while(j<=r) b[t++] = a[j++];
for (int i = 0;i<t;i++)
a[l + i] = b[i];//把排序号的b[]复制给a[]
}
void Mergesort(ll l,ll r)
{
if(l<r)
{
ll mid = (l + r) >> 1;
Mergesort(l, mid);
Mergesort(mid + 1, r);
Merge(l, mid, r);
}
}
int main()
{
a[0] = 4;
a[1] = 1;
a[2] = 3;
a[3] = 2;
a[4] = 4;
a[5] = 8;
a[6] = 15;
Mergesort(0, 6);
for (int i = 0;i<=6;i++)
cout << a[i] << " ";
return 0;
}