hdu1394 Minimum Inversion Number 线段树

首先是题目:找出几个序列的逆序数,并输出其中最小的逆序数。

线段树:读入第n个数,树的叶子代表的是——在n之前读入的数的出现 ,比如当读入1时 ,在此之前已经读入了2 ,则树的第二个叶子就设置为1 (1表示出现过,开始初始化为0),在此之前已经读入了3,则树的第三个叶子就设置为1。树的父节点就是统计区间的和 。利用query(n)统计有多少个比n小的数出现过 。

最基础的线段树是记录数列的值,求其和。在这道题里是记录出现次数,和就是求在某个区间内的有多少个比特定值小的数出现了。

#include <iostream>
#define MAX 20000
using namespace std;
int tree[MAX];
void pushup(int rt)
{
    tree[rt]=tree[rt<<1]+tree[rt<<1|1];
}
void buildtree(int l,int r,int rt)
{
    tree[rt]=0;
    if(l==r) return ;
    int m=(l+r)>>1;
    buildtree(l,m,rt<<1);
    buildtree(m+1,l,rt<<1|1);
}
void update(int l,int r,int rt,int k,int num)
{
    if(l==r) 
    {
        tree[rt]=1;
        return;
    }
    int m=(l+r)>>1;
    if(k<m) update(l,m,rt<<1,k,num);
    else update(m+1,r,rt<<1|1,k,num);
    pushup(rt);
    
}
int query(int l,int r, int rt,int a,int b)
{
    if(a<=l&&r>=b) return tree[rt];
    int m=(l+r)>>1;
    int all=0;
    if(a<=m) all+=query(l,m,rt<<1,a,b);
    if(m<b)   all+=query(m+1,r,rt<<1|1,a,b);
    return all; 
    
}

posted @ 2018-03-16 20:33  LandingGuys  阅读(85)  评论(0编辑  收藏  举报