HDU 4911 Inversion 解题报告(逆序数)

Inversion

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


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
 
    解题报告:求逆序数inv,输出max(inv-k, 0)即可。这里用线段树求逆序数。代码如下:
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <queue>
#include <vector>
#include <map>
#include <set>
#include <string>
#include <iomanip>
using namespace std;
#define ff(i, n) for(int i=0;i<(n);i++)
#define fff(i, n, m) for(int i=(n);i<=(m);i++)
#define dff(i, n, m) for(int i=(n);i>=(m);i--)
#define bit(n) (1LL<<(n))
typedef long long LL;
typedef unsigned long long ULL;
const LL inf=1e15;
void work();
int main()
{
#ifdef ACM
    freopen("input.in", "r", stdin);
#endif // ACM
    work();
}

/***************************************************/

#define lson l, m, pos<<1
#define rson m+1, r, pos<<1|1
#define defm int m = (l+r)/2;

const int maxn = 111111;
int num[111111];
int yy[111111];
int n, k;

LL sum[maxn << 2];
void updateFather(int pos)
{
    sum[pos] = sum[pos<<1] + sum[pos<<1|1];
}
void update(int p, int l, int r, int pos)
{
    if(l == r)
    {
        sum[pos]++;
        return;
    }

    defm;
    if(p <= m)
        update(p, lson);
    else
        update(p, rson);
    updateFather(pos);
}

LL query(int L, int R, int l, int r, int pos)
{
    if(L<=l && r<=R)
        return sum[pos];
    defm;
    return (L<=m?query(L, R, lson):0) + (m<R?query(L, R, rson):0);
}

void work()
{
    while(scanf("%d%d", &n, &k) == 2)
    {
        ff(i, n) scanf("%d", num + i);
        memcpy(yy, num, sizeof(num));
        sort(yy, yy+n);
        int tot = unique(yy, yy+n) - yy;

        LL ans = 0;
        memset(sum, 0, sizeof(sum));
        ff(i, n)
        {
            int pos = lower_bound(yy, yy+tot, num[i]) - yy;
            ans += query(pos+1, tot, 0, tot, 1);
            update(pos, 0, tot, 1);
        }

        cout << max(ans - k, 0LL) << endl;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值