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");
    }
}

 

posted @ 2017-08-19 09:20  joeylee97  阅读(199)  评论(0编辑  收藏  举报