HDU 1394 线段树求逆序数 + 递推逆序数

n个数的排列,一个数a[i](0 <= a[i] < n),它在这个排列中,大于它的数有n - a[i] - 1个,小于它的数有a[i]个,将它放到最后,大于它的数变为逆序,小于它的数变为顺序,逆序数 = 变化前的逆序数 + n - a[i] - 1 - a[i].

#include <set>
#include <map>
#include <cmath>
#include <queue>
#include <stack>
#include <vector>
#include <cstdio>
#include <string>
#include <cctype>
#include <climits>
#include <cstring>
#include <cstdlib>
#include <iostream>
#include <algorithm>
using namespace std;
class ST
{
private:
    int n, a[5005], b[5005 * 4], ans, inv;
public:
    void pushup(int rt)
    {
        b[rt] = b[rt << 1] + b[rt << 1 | 1];
    }
    void build(int _l, int _r, int rt)
    {
        b[rt] = 0;
        if (_l == _r)
            return ;
        int m = _l + (_r - _l) / 2;
        build(_l, m, rt << 1);
        build(m + 1, _r, rt << 1 | 1);
    }
    void update(int p, int _l, int _r, int rt)
    {
        if (_l == _r)
        {
            b[rt]++;
            return ;
        }
        int m = _l + (_r - _l) / 2;
        if (p <= m)
            update(p, _l, m, rt << 1);
        else
            update(p, m + 1, _r, rt << 1 | 1);
        pushup(rt);
    }
    int query(int L, int R, int _l, int _r, int rt)
    {
        if (_l <= L && _r >= R)
            return b[rt];
        int m = L + (R - L) / 2;
        int ret = 0;
        if (_l <= m)
            ret += query(L, m, _l, _r, rt << 1);
        if (_r > m)
            ret += query(m + 1, R, _l, _r, rt << 1 | 1);
        return ret;
    }
    bool Input()
    {
        if (~scanf("%d", &n))
        {
            inv = 0;
            build(0, n - 1, 1);
            for (int i = 0; i < n; i++)
            {
                scanf("%d", &a[i]);
                inv += query(0, n - 1, a[i], n - 1, 1);
                update(a[i], 0, n - 1, 1);
            }
            return true;
        }
        return false;
    }
    void Output()
    {
        ans = inv;
        for (int i = 0; i < n; i++)
        {
            inv += n - a[i] - 1 - a[i];
            ans = min(ans, inv);
        }
        printf("%d\n", ans);
    }
} stree;
int main()
{
    while (stree.Input())
        stree.Output();
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值