Code:

#include<bits/stdc++.h>
using namespace std;
#define setIO(s) freopen(s".in","r",stdin)
#define maxn 200000
#define inf 10000000000000
#define get(x) (ch[f[x]][1]==x)
#define ll long long
int root,cc,kk;
int h[maxn],ch[maxn][2],f[maxn],siz[maxn],val[maxn];
long long sumv[maxn];
long long ans=inf;
void pushup(int x)
{
sumv[x]=sumv[ch[x][0]]+sumv[ch[x][1]]+h[x];
siz[x]=siz[ch[x][0]]+siz[ch[x][1]]+1;
}
void rotate(int x)
{
int old=f[x],fold=f[old],which=get(x);
ch[old][which]=ch[x][which^1],f[ch[old][which]]=old;
ch[x][which^1]=old,f[old]=x,f[x]=fold;
if(fold) ch[fold][ch[fold][1]==old]=x;
pushup(x),pushup(old);
}
void splay(int x,int &tar)
{
int u=f[tar];
for(int fa;(fa=f[x])!=u;rotate(x))
if(f[fa]!=u)
rotate(get(fa)==get(x)?fa:x);
tar=x;
}
void insert(int &x,int key,int ff)
{
if(!x) x=key,f[x]=ff;
else insert(ch[x][h[key]>h[x]],key,x);
pushup(x);
}
int query(int kth)
{
int x=root;
while(1)
{
if(siz[ch[x][0]]+1==kth) return x;
if(siz[ch[x][0]]>=kth) x=ch[x][0];
else kth-=(siz[ch[x][0]]+1),x=ch[x][1];
}
}
void del(int x)
{
if(!ch[x][0]) root=ch[x][1], f[root]=ch[x][1]=0;
else if(!ch[x][1]) root=ch[x][0], f[root]=ch[x][0]=0;
else
{
int l=ch[x][0];
while(ch[l][1]) l=ch[l][1];
splay(l, ch[x][0]);
ch[l][1]=ch[x][1], f[ch[x][1]]=l, f[l]=ch[x][0]=ch[x][1]=0, pushup(l);
root=l;
}
}
void solve(int k,int L)
{
int mid=(k%2==0)?k/2:(k/2)+1,x=query(mid);
splay(x,root);
int l=ch[root][0],r=ch[root][1];
ll re=0;
re+=(h[x]*siz[l]-sumv[l]);
re+=(sumv[r]-h[x]*siz[r]);
if(re<ans) ans=re, cc=L, kk=h[x];
}
int main()
{
// setIO("input");
int n,k,i,j;
scanf("%d%d",&n,&k);
for(i=1;i<=n;++i) scanf("%d",&h[i]);
for(i=1;i<=k;++i) { insert(root,i,0); if(i%6==0) splay(i,root); }
solve(k,1);
for(i=k+1;i<=n;++i)
{
j=i-k+1;
splay(j-1, root), del(j-1), insert(root,i,0), splay(i,root), solve(k,j);
}
printf("%lld\n",ans);
return 0;
}

  

最新文章

  1. LeetCode 3 Longest Substring Without Repeating Characters 区间,想法 难度:1
  2. 总结一下使用react-native的一些入门级重要点
  3. jsp应用
  4. C#表达式树的初步了解
  5. CRLF CSRF XSS
  6. PHP强制清除缓存
  7. 【补解体报告】topcoder 634 DIV 2
  8. android 链接蓝牙不稳定的解决建议
  9. c++给数组赋值
  10. listener笔记
  11. Office 2010 &amp; SharePoint 2010 Service Pack 2现在可用啦
  12. java 采用MD5加密解密
  13. PowerDesigner有几个需要设置
  14. mac下git配置和jenkins打包
  15. 弹性布局Flex的基本语法
  16. 3D Math Keynote 3
  17. POJ1509 Glass Beads(最小表示法 后缀自动机)
  18. Cyclic Nacklace hdu3746 kmp 最小循环节
  19. [ZJOI2010]贪吃的老鼠
  20. Nginx 如何限定IP访问

热门文章

  1. 【GIS数据处理】 利用空间关系建立线CAD数据和属性表关联
  2. curl 使用 post 请求,传递 json 参数,下载文件
  3. vi, Java, Ant, Junit自学报告 - 实训week1
  4. 类LinkedHashSet
  5. 5 centos 6.10 三节点安装apache hadoop 2.9.1
  6. 06 使用bbed修复delete的数据--01
  7. Cors 跨域 共享
  8. Node.js实战9:用EventEmitter触发和响应事件。
  9. python基础-6.2正则表达式,计算器练习
  10. JavaSE编码试题强化练习5