Inversion 归并求逆元

Posted joeylee97

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Inversion 归并求逆元相关的知识,希望对你有一定的参考价值。

bobo has a sequence a 1,a 2,…,a n. He is allowed to swap twoadjacent 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.

InputThe 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).OutputFor each tests: 

A single integer denotes the minimum number of inversions.

 

 

#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<sstream>
#include<algorithm>
#include<queue>
#include<vector>
#include<cmath>
#include<map>
#include<stack>
#include<set>
#include<memory>
#include<bitset>
#include<string>
#include<functional>
using namespace std;
typedef long long LL;
typedef unsigned long long ULL;

const int MAXN = 1e5 + 9;
#define INF 0x3f3f3f3f
//
LL n, k, cnt = 0;
LL a[MAXN], L[MAXN/2], R[MAXN];
void merge(LL l, LL r)
{
    LL mid = (l + r) / 2;
    LL t1 = 0, t2 = 0;
    for (LL i = l; i <= mid; i++)
        L[t1++] = a[i];
    for (LL i = mid + 1; i <= r; i++)
        R[t2++] = a[i];
    LL i = 0, j = 0, pos = l;
    while (i < t1&&j < t2)
    {
        if (L[i] > R[j])
        {
            cnt += (t1 - i);
            a[pos++] = R[j++];
        }
        else
            a[pos++] = L[i++];
    }
    while (i < t1)
        a[pos++] = L[i++];
    while (j < t2)
        a[pos++] = R[j++];
}
void merge_sort(LL l, LL r)
{
    if (l < r)
    {
        LL mid = (l + r) / 2;
        merge_sort(l, mid);
        merge_sort(mid + 1, r);
        merge(l, r);
    }
}
int main()
{
    while (scanf("%lld%lld", &n, &k) != EOF)
    {
        cnt = 0;
        for (LL i = 0; i < n; i++)
        {
            scanf("%lld", &a[i]);
        }
        merge_sort(0, n - 1);
        if (cnt >= k)
            printf("%lld\n", cnt - k);
        else
            printf("0\n");
    }
}

 

以上是关于Inversion 归并求逆元的主要内容,如果未能解决你的问题,请参考以下文章

求逆元的四大基本方法

线性求逆元

求逆元

AcWing 876. 快速幂求逆元

数论——快速幂,模运算及快速幂求逆元

求逆元的常用方法