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为止,所以不需要&&n,在每一次重新输入数据之后要记得将求得的和清零。利用归并思想是很好的方法。
程序代码:
#include<cstdio>
#include<iostream>
using namespace std;
long long k;
const int maxn=100005;
long long a[maxn],v[maxn];
int mer_sort(long long x,long long y)
{
if(x<y)
{
long long m=(y+x)/2;
mer_sort(x,m);
mer_sort(m+1,y);
int p=0,q=m+1,i=x;
while(i<=m&&q<=y)
{
if(a[i]>a[q])
{v[p++]=a[q++];k+=m+1-i;}
else v[p++]=a[i++];
}
while(i<=m)
v[p++]=a[i++];
while(q<=y)
v[p++]=a[q++];
for(i=0;i<p;++i)
a[x+i]=v[i];
}
return 0;
}
int main()
{
long long n,t;
while(scanf("%lld%lld",&n,&t)!=EOF)
{k=0;
for(int i=0;i<n;i++)
scanf("%lld",&a[i]);
mer_sort(0,n-1);
if(k<=t)printf("0
");
else
printf("%lld
",k-t);
}
return 0;
}