HDU-4911 Inversion(逆序对性质)

Inversion

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 131072/131072 K (Java/Others)
Total Submission(s): 6318    Accepted Submission(s): 2165


 

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

 

根据逆序数的定理

如果逆序数大于0,那么必定存在1<=i<n使得i和i+1交换后逆序数减1

假设原逆序数为cnt,这样的话,我们就可以得到答案是max(cnt-k,0)

求逆序数可以用归并的方法

 

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
#define maxn 100010
int a[maxn],rrr[maxn],n,k;//ans作为全局变量,记录逆序对的数量;
long long ans;
void mergesort(int l,int r)
{
     if(r==l) return;
     int mid=(l+r)/2;
    mergesort(l,mid);
    mergesort(mid+1,r);
    int i=l,j=mid+1,k=l;//i是最左边的那个数,j是中间偏右的第一个数,这样也是对称比较 明白两个数,三个数的交换就行。

                                 //mid要么再中间,要么再偏左位置
        while(i<=mid&&j<=r){
        if(a[i]<=a[j])
            rrr[k]=a[i],k++,i++;
        else{
            rrr[k]=a[j],k++,j++;
            ans+=mid-i+1;//一半再加中点,前面的数比你大,后面的数肯定也比你大,所以求的逆序数就是一段区间
        }
    }
    while(i<=mid)
        rrr[k]=a[i],k++,i++;
    while(j<=r)
        rrr[k]=a[j],k++,j++;
    for(int i=l;i<=r;i++)
        a[i]=rrr[i];
}
int main()
{
    while(scanf("%d%d",&n,&k)!=EOF)
    {
         ans=0;             //额,数量较大就得考虑long long
         memset(a,0,sizeof(a));
         for(int i=1;i<=n;i++)
         scanf("%d",&a[i]);
         mergesort(1,n);//从1到n将a数组排序;
         printf("%lld\n",max(ans-k,(long long)0));
    }
    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值