hdu_1394,线段树求逆序数

http://www.notonlysuccess.com/index.php/segment-tree-complete/
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
using namespace std;
const int maxn=5555;
int sum[maxn<<2];
int seq[maxn];
void pushUp(int rt)
{
    sum[rt]=sum[rt<<1]+sum[rt<<1|1];
}
void build(int l,int r,int rt)
{
    if(r==l)
    {
        sum[rt]=0;
        return;
    }
    int m=(r+l)>>1;
    build(lson);
    build(rson);
}
void update(int L,int d,int l,int r,int rt)
{
    if(l==r)
    {
        sum[rt]=d;
        return;
    }
    int m=(r+l)>>1;
    if(L<=m) update(L,d,lson);
    else update(L,d,rson);
    pushUp(rt);
}
int query(int L,int R,int l,int r,int rt)
{
    int ret=0;
    if(L<=l&&r<=R){return sum[rt];}
    int m=(l+r)>>1;
    if(L<=m) ret+=query(L,R,lson);
    if(R>m) ret+=query(L,R,rson);
    return ret;
}
int main()
{
    int n;
    while(scanf("%d",&n)!=EOF)
    {
        int ans=0;
        memset(sum,0,sizeof(sum));
        build(0,n-1,1);
        memset(seq,0,sizeof(seq));
        for(int i=0;i<n;i++)
        {
            scanf("%d",&seq[i]);
            ans+=i-query(0,seq[i],0,n-1,1);
            //cout<<ans<<" ";
            //cout<<endl;
            update(seq[i],1,0,n-1,1);
        }
        int cur=ans;
        for(int i=0;i<n;i++)
        {
            cur+=n-seq[i]*2-1;
            ans=min(ans,cur);
        }
        cout<<ans<<endl;
    }
    return 0;
}

posted @ 2014-09-11 20:02  JarvisLau  阅读(157)  评论(0编辑  收藏  举报