您的位置:首页 > 其它

hdu 4911 Inversion

2015-06-03 20:37 405 查看


Inversion

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 131072/131072 K (Java/Others)

Total Submission(s): 2222 Accepted Submission(s): 859



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


Author

Xiaoxu Guo (ftiasch)

Source

2014 Multi-University Training Contest 5

Recommend

We have carefully selected several similar problems for you: 5257 5256 5255 5254 5253

题意:输入n,k n为序列的长度,k为交换的次数,每次只能是相邻元素之间的交换,求该序列经过k次交换得到最小的逆序数。

若1个序列的逆序数大于0,总存在0<=i<n使得 swap(ai,ai+1)之后 逆序数减1;

因此用归并排序求出序列的逆序数cnt与k进行比较即可得到答案

还要注意 用int存储逆序数会数据溢出

AC代码:

#include <stdio.h>
#include "string.h"
#include "math.h"
long long int cnt;
void Merge(int ss[],int ex,int ey,int sx,int sy)
{
int temp[100002],i=ex,j=sx,pos=ex;
for(;i<=ey&&j<=sy;)
{
if(ss[i]<=ss[j])
temp[pos++]=ss[i++];
else
{
temp[pos++]=ss[j++];
cnt+=(ey-i+1);
}
}
while(i!=ey+1)
temp[pos++]=ss[i++];
while(j!=sy+1)
temp[pos++]=ss[j++];
for(i=ex;i<=sy;i++)
{
ss[i]=temp[i];
}
}

void Mergesort(int ss[],int left,int right)
{
int middle;
if(left<right)
{
middle=(left+right)/2;
Mergesort(ss,left,middle);
Mergesort(ss, middle+1, right);
Merge(ss,left,middle,middle+1,right);
}
}
int main()
{
int n,k;

while(scanf("%d%d",&n,&k)!=EOF)
{
int ss[100002];
cnt=0;
for(int i=0;i<n;i++)
scanf("%d",&ss[i]);
Mergesort(ss, 0, n-1);
if(k>cnt) printf("0\n");
else printf("%lld\n",cnt-k);
}
}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: