【HDU4911】分治求逆序数

Inversion

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


Problem 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
 

Author
Xiaoxu Guo (ftiasch)
 

Source
 
#define DeBUG
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <cstdlib>
#include <algorithm>
#include <vector>
#include <stack>
#include <queue>
#include <string>
#include <set>
#include <sstream>
#include <map>
#include <list>
#include <bitset>
using namespace std ;
#define zero {0}
#define INF 0x3f3f3f3f
#define EPS 1e-6
#define TRUE true
#define FALSE false
typedef long long LL;
const double PI = acos(-1.0);
//#pragma comment(linker, "/STACK:102400000,102400000")
inline int sgn(double x)
{
    return fabs(x) < EPS ? 0 : (x < 0 ? -1 : 1);
}
#define N 1000005
int p[N], t[N];
long long anti;//保存逆序数结果
int a[N];
void merge(int first, int last)
{
    int mid = (first + last) / 2;
    int i1 = 0, i2 = first, i3 = mid + 1;
    while (i2 <= mid && i3 <= last)
    {
        if (p[i2] > p[i3])
        {
            t[i1++] = p[i3++];
            anti += mid - i2 + 1;
        }
        else
            t[i1++] = p[i2++];
    }
    while (i2 <= mid)
    {
        t[i1++] = p[i2++];
    }
    while (i3 <= last)
    {
        t[i1++] = p[i3++];
    }
    i1 = first;
    i2 = 0;
    while (i2 < last - first + 1)
    {
        p[i1++] = t[i2++];
    }
}
void merge_sort(int first, int last)
{
    int mid;
    if (first < last)
    {
        mid = (first + last) / 2;
        merge_sort(first, mid);
        merge_sort(mid + 1, last);
        merge(first, last);
    }
}
int main()
{
#ifdef DeBUGs
    freopen("C:\\Users\\Sky\\Desktop\\1.in", "r", stdin);
#endif
    int n, k;
    while (scanf("%d%d", &n, &k) + 1)
    {
        anti = 0;
        memset(p,0,sizeof(p));
        memset(t,0,sizeof(t));
        for (int i = 0; i < n; i++)
        {
            scanf("%d", &p[i]);
        }
        merge_sort(0, n-1);
        if (k > anti)
            cout<<0<<endl;
        else
            cout<<anti-k<<endl;
    }

    return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值