hdu 4911(归并排序经典题)

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.

分析:注意此题的交换只能在相邻元素间进行,并不能任意交换!!!
因此想到了归并排序,因为归并排序的基础为交换元素,可视为一种加强版的选择排序(都通过交换元素进行)
因此在归并排序中左边序列大于右边序列时就会出现逆序对,查找左序列中在a[i]右侧的数据个数即为逆序数
但因为可以交换k次,每交换一次就减少一个逆序数,即当cnt>k时,结果为cnt-k 小于等于时说明cnt为0(全都交换完了)

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll maxn=100005;
ll a[maxn],b[maxn],cnt;
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++];
            cnt+=mid-i+1;
        }
        else
        {
            b[t++]=a[i++];
        }
    }

    while(i<=mid) b[t++]=a[i++];
    while(j<=r) b[t++]=a[j++];
    for(i=0;i<t;i++) a[l+i]=b[i];
}

void Mergesort(ll l,ll r)
{
    if(l<r)
    {
        ll mid=(l+r)/2;
        Mergesort(l,mid);
        Mergesort(mid+1,r);
        Merge(l,mid,r);
    }
}
int main()
{
    ll n,k;
    while(cin>>n>>k)
    {
        cnt=0;
        for(ll i=0;i<n;i++)
        {
            cin>>a[i];
        }
        Mergesort(0,n-1);
        if(cnt<=k) cout<<0<<endl;
        else cout<<cnt-k<<endl;
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值