[vijos1459]车展(splay)

题目描述

传送门

题解

在splay里维护一下子树的size和sum。
n2 枚举区间,每次加一个点,然后查询中位数。用size和sum计算一下答案。
预处理出来 n2 个区间了之后直接统计答案即可。

代码

#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
#define LL long long
#define N 1000005

int n,m,l,r,root,sz;
LL h[1005];
int f[N],ch[N][2];
LL size[N],cnt[N],sum[N],key[N];
LL cost[1005][1005],ans;

int get(int x)
{
    return ch[f[x]][1]==x;
}
void update(int x)
{
    size[x]=size[ch[x][0]]+size[ch[x][1]]+cnt[x];
    sum[x]=sum[ch[x][0]]+sum[ch[x][1]]+cnt[x]*key[x];
}
void rotate(int x)
{
    int old=f[x],oldf=f[old],wh=get(x);
    ch[old][wh]=ch[x][wh^1];
    f[ch[old][wh]]=old;
    ch[x][wh^1]=old;
    f[old]=x;
    if (oldf) ch[oldf][ch[oldf][1]==old]=x;
    f[x]=oldf;
    update(old);
    update(x);
}
void splay(int x)
{
    for (int fa;fa=f[x];rotate(x))
        if (f[fa])
            rotate( (get(x)==get(fa))?fa:x );
    root=x; 
}
void insert(int x)
{
    if (!root)
    {
        root=++sz;
        size[sz]=cnt[sz]=1;
        key[sz]=sum[sz]=x;
        return;
    }
    int now=root,fa=0;
    while (1)
    {
        if (x==key[now])
        {
            ++cnt[now];
            update(now);
            splay(now);
            return;
        }
        fa=now;
        now=ch[now][x>key[now]];
        if (!now)
        {
            ++sz;
            f[sz]=fa;ch[fa][x>key[fa]]=sz;
            size[sz]=cnt[sz]=1;
            key[sz]=sum[sz]=x;
            splay(sz);
            return;
        }
    }
}
int find(int x)
{
    int now=root;
    while (1)
    {
        if (x<=size[ch[now][0]]) now=ch[now][0];
        else
        {
            x-=size[ch[now][0]];
            if (x<=cnt[now]) return now;
            x-=cnt[now];
            now=ch[now][1];
        }
    }
}
int main()
{
    scanf("%d%d",&n,&m);
    for (int i=1;i<=n;++i) scanf("%lld",&h[i]);
    l=1;
    while (l<=n)
    {
        r=l;root=0;
        while (r<=n)
        {
            insert(h[r]);
            int x=find(((r-l+1)>>1)+1);
            splay(x);
            cost[l][r]=key[root]*size[ch[root][0]]-sum[ch[root][0]]+sum[ch[root][1]]-key[root]*size[ch[root][1]];
            ++r;
        }
        ++l;
    }
    for (int i=1;i<=m;++i)
    {
        scanf("%d%d",&l,&r);
        if (l>r) swap(l,r);
        ans+=cost[l][r];
    }
    printf("%lld\n",ans);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值