hdu 4911 归并排序求逆序数

本文介绍了一种通过归并排序算法来求解给定序列在允许交换相邻元素k次的情况下,能够达到的最小逆序数的方法。核心思路在于先计算序列的初始逆序数,然后减去最多可以进行的k次优化操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

题解:

用归并排序求出逆序数,题意是只能交换k次相邻的数,所以答案为cnt-k,但是不能为负数,所以答案为max(cnt-k,0)

代码:

#include <iostream>
#include <cstring>
#include <algorithm>

using namespace std;
typedef long long LL;
const LL maxn = 1e5+10;
LL cnt;
void merge_sort(LL A[],int x,int y,LL T[])
{
    if(y-x>1)
    {
        int m = x+(y-x)/2;  //划分
        int p=x,q=m,i=x;
        merge_sort(A,x,m,T);
        merge_sort(A,m,y,T);
        while(p<m||q<y)
        {
            if(q>=y||(p<m&&A[p]<=A[q]))
                T[i++]=A[p++];
            else
                {T[i++]=A[q++];cnt+=m-p;}
        }
        for(i=x;i<y;i++) A[i]=T[i];
    }
}

int main()
{
    LL n,k;
    LL A[maxn];
    LL T[maxn];
    while(cin>>n>>k)
    {
        memset(T,0,sizeof(T));
        memset(A,0,sizeof(A));
      cnt=0;
      for(int i=0;i<n;i++)
        cin>>A[i];
      merge_sort(A,0,n,T);
      cout<<max(cnt-k,(LL)0)<<endl;
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值