hdu 1394 Minimum Inversion Number 线段树

17 篇文章 0 订阅
题意:求a1, a2, ..., an-1, an (where m = 0 - the initial seqence)
                a2, a3, ..., an, a1 (where m = 1)
                a3, a4, ..., an, a1, a2 (where m = 2)
                ...

                an, a1, a2, ..., an-1 (where m = n-1)    这n个序列的逆序数的最小值。

考虑已经得到第一组序列的逆序数,设第一个数为x,则对于x在第一组序列中将凑出x个逆序数(因为是0~n-1),将第一项移到最后,原来的对第一个数x构成的逆序数对总数就会减少x,而增加的逆序数对就是没有与x构成逆序数对的数量,即n-1-x。那么将x移到最后的操作的贡献就是n-1-2*x。然后求出所有的数的贡献,从第一组序列开始依次遍历过去通过贡献计算该序列的逆序数对即可

#include <bits/stdc++.h>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <cmath>
#include <time.h>
#include <vector>
#include <cstdio>
#include <string>
#include <iomanip>
///cout << fixed << setprecision(13) << (double) x << endl;
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <algorithm>

using namespace std;

#define lson l, mid, rt << 1
#define rson mid + 1, r, rt << 1 | 1
#define ls rt << 1
#define rs rt << 1 | 1
#define pi acos(-1.0)
#define eps 1e-8
#define Mp(a, b) make_pair(a, b)
#define asd puts("asdasdasdasdasdf");
typedef long long ll;
typedef pair <int, int> pl;
//typedef __int64 LL;
const int inf = 0x3f3f3f3f;
const int N = 5050;

struct node{
    int l, r, x;
}tr[N<<2];
int n;
int a[N];

void pushup( int rt )
{
    tr[rt].x = tr[ls].x + tr[rs].x;
}

void build( int l, int r, int rt )
{
    tr[rt].l = l;
    tr[rt].r = r;
    tr[rt].x = 0;
    if( l == r )
        return;
    int mid = ( l + r ) >> 1;
    build( lson );
    build( rson );
}

void update( int rt, int x )
{
    if( tr[rt].l == tr[rt].r ) {
        tr[rt].x++;
        return;
    }
    int mid = ( tr[rt].l + tr[rt].r ) >> 1;
    if( x <= mid )
        update( ls, x );
    else
        update( rs, x );
    pushup( rt );
}

int query( int l, int r, int rt )
{
    if( l <= tr[rt].l && tr[rt].r <= r )
        return tr[rt].x;
    int mid = ( tr[rt].l + tr[rt].r ) >> 1;
    int res = 0;
    if( l <= mid )
        res += query( l, r, ls );
    if( r > mid )
        res += query( l, r, rs );
    return res;
}

int main()
{
    while( ~scanf("%d", &n) ) {
        build( 0, n-1, 1 );
        int inv_num = 0, ans;
        for( int i = 0; i < n; ++i ) {
            scanf("%d", &a[i]);
            inv_num += query( a[i]+1, n-1, 1 );    //统计逆序数
            update( 1, a[i] );
        }
        ans = inv_num;  //第一个序列逆序数
        for( int i = 0; i < n; ++i ) {
            inv_num += ( n - 1 - 2 * a[i] );    //每次队首移到队尾逆序数变化量
            ans = min( ans, inv_num );
        }
        printf("%d\n", ans);
    }
    return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值