HDU 4911 Inversion (逆序数 归并排序)

Inversion

题目链接:

http://acm.hust.edu.cn/vjudge/contest/121349#problem/A

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.

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).

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


题意:


对有n个元素的数组进行不超过k次操作,每次操作允许交换相邻元素;
求操作后能得到的整个数组的最小逆序数.


题解:


容易得出每次交换相邻元素最多只能使得逆序数降低1.
而对于一个逆序数不为0的数组,一定存在相邻的两个数满足(i < j, ai < aj)(可反证).
所以每次操作都可以使得逆序数减少1. 最终答案即为max(0, 逆序数).
求逆序数可以用归并排序、树状数组和线段树(数的规模较小时).


代码:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <queue>
#include <map>
#include <set>
#include <vector>
#define LL long long
#define eps 1e-8
#define maxn 101000
#define mod 100000007
#define inf 0x3f3f3f3f
#define IN freopen("in.txt","r",stdin);
using namespace std;

LL num[maxn];
LL _count=0;

void merge_array(int left,int mid,int right)
{
    int temp[right-left+1];int k=0;
    int i=left;int j=mid+1;
    while(i<=mid&&j<=right)
    {
        if(num[i]<=num[j])
            temp[k++]=num[i++];
        else
            {temp[k++]=num[j++];_count+=mid-i+1;}
    }
    while(i<=mid)
        temp[k++]=num[i++];
    while(j<=right)
        temp[k++]=num[j++];

    for(i=left;i<=right;i++)
        num[i]=temp[i-left];
}


void merge_sort(int left,int right)
{
    if(left<right)
    {
        int mid=left+(right-left)/2;
        merge_sort(left,mid);
        merge_sort(mid+1,right);
        merge_array(left,mid,right);
    }
}

int main(void)
{
    //IN;

    int n;
    LL k;
    while(scanf("%d %I64d",&n,&k) != EOF)
    {
        for(int i=0; i<n; i++)
            scanf("%I64d",&num[i]);
        _count=0;
        merge_sort(0, n-1);

        printf("%I64d\n", max(_count-k,0LL));
    }
    return 0;
}

转载于:https://www.cnblogs.com/Sunshine-tcf/p/5719053.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值