LOJ #10143 BZOJ P1588「HNOI2002」营业额统计【Splay】【已更新错误】

一道经典的平衡树板子题。

我记得之前写这道题的题解的时候,写的是“查询根节点的前驱后继与它本身做差取最小”,但是这样的说法其实有一个问题。

“前驱”的定义是小于 x x x的最大值。

注意,在定义中是不能取等的,但是这道题根据题目的意思显然可以取等,也就是说,这道题要求的并不是严格的“前驱”与“后继”。

所以我们在插入值之后,应该要先判断一下 c n t [ r o o t ] cnt[root] cnt[root]的值,然后再考虑是否去求前驱与后继。

#include<cstdio>

const int N=1e5+5;
const int inf=1e9;

int n,ans,rt,tot,fa[N],ch[N][2],val[N],cnt[N],sz[N];

struct Splay {
    void maintain(int x) {
        sz[x]=sz[ch[x][0]]+sz[ch[x][1]]+cnt[x];
    }
    
    bool get(int x) {
        return x==ch[fa[x]][1];
    }
    
    void clear(int x) {
        ch[x][0]=ch[x][1]=fa[x]=val[x]=sz[x]=cnt[x]=0;
    }
    
    void rotate(int x) {
        int y=fa[x],z=fa[y],chk=get(x);
        ch[y][chk]=ch[x][chk^1]; fa[ch[x][chk^1]]=y; ch[x][chk^1]=y;
        fa[y]=x; fa[x]=z;
        if(z) ch[z][y==ch[z][1]]=x;
        maintain(x); maintain(y);
    }
    
    void splay(int x) {
        for(int f=fa[x];f=fa[x],f;rotate(x))
            if(fa[f]) rotate(get(x)==get(f)?f:x);
        rt=x;
    }
    
    void ins(int k) {
        if(!rt) {
            val[++tot]=k;
            cnt[tot]++;
            rt=tot;
            maintain(rt);
            return;
        }
        int cnr=rt,f=0;
        while(1) {
            if(val[cnr]==k) {
                cnt[cnr]++;
                maintain(cnr); maintain(f);
                splay(cnr);
                break;
            }
            f=cnr;
            cnr=ch[cnr][val[cnr]<k];
            if(!cnr) {
                val[++tot]=k;
                cnt[tot]++;
                fa[tot]=f;
                ch[f][val[f]<k]=tot;
                maintain(tot); maintain(f);
                splay(tot);
                break;
            }
        }
    }
    
    int pre() {
        int cnr=ch[rt][0];
        if(!cnr) return inf;
        while(ch[cnr][1]) cnr=ch[cnr][1];
        return val[cnr];
    }
    
    int nxt() {
        int cnr=ch[rt][1];
        if(!cnr) return inf;
        while(ch[cnr][0]) cnr=ch[cnr][0];
        return val[cnr];
    }
}Tree;

inline int abs(int x){return x>0?x:-x;}
inline int min(int x,int y){return x>y?y:x;}

int main() {
	scanf("%d",&n);
	
	for(int i=1;i<=n;i++) {
		int x;
		scanf("%d",&x);Tree.ins(x);
		if(i==1) ans=x;
		else if(cnt[rt]>1) continue;
		else ans+=min(abs(x-Tree.pre()),abs(x-Tree.nxt()));
	}
	
	printf("%d",ans);
	
    return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值