题目描述
题解
在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);
}