题意

大力猜结论。

首先将所有\(a_i\)变为\(a_i-i\),之后求不严格递增的\(b_i\),显然答案不变,最后\(b_i\)加上\(i\)即可。

考虑两种特殊情况:

1.\(a[]\)是递增的:所有\(b_i=a_i\)。

2.\(a[]\)是递减的:显然取\(a[]\)的中位数\(x\),所有\(b_i=x\)。

现在考虑\(a[]\)一段递增一段递减这样排列,我们可以对每一段递减的\(a_i,a_{i+1}...a_{i+k}\)求出中位数\(c_i\)。

现在我们的\(a[]\)变成了\(c_1,c_2...c_k\)的形式,考虑如果还有\(c_{i+1}<c_i\),我们就合并\(i,i+1\)两段,求出它们的中位数作为新的一段的值。

合并求中位数可以用左偏树完成,我们只需要对每一段开一个左偏树,只保留段数的一半个数,每次合并后就暴力弹出。

code:

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn=1000010;
int n,top;
ll ans;
ll a[maxn],b[maxn];
struct Heap
{
#define lc(p) (heap[p].lc)
#define rc(p) (heap[p].rc)
#define dis(p) (heap[p].dis)
int lc,rc,dis;
}heap[maxn];
struct node
{
int root,l,r,size;
ll k;
}sta[maxn];
int merge(int x,int y)
{
if(!x||!y)return x+y;
if(a[x]<a[y])swap(x,y);
rc(x)=merge(rc(x),y);
if(dis(rc(x))>dis(lc(x)))swap(lc(x),rc(x));
dis(x)=dis(rc(x))+1;
return x;
}
int main()
{
scanf("%d",&n);
for(int i=1;i<=n;i++)scanf("%lld",&a[i]),a[i]-=i;
for(int i=1;i<=n;i++)
{
sta[++top]=(node){i,i,i,1,a[i]};
while(top>1&&sta[top].k<sta[top-1].k)
{
sta[top-1].root=merge(sta[top-1].root,sta[top].root);
sta[top-1].size+=sta[top].size;
sta[top-1].r=sta[top].r;
while(sta[top-1].size>(sta[top-1].r-sta[top-1].l+1-1)/2+1)
{
sta[top-1].size--,sta[top-1].root=merge(lc(sta[top-1].root),rc(sta[top-1].root));
}
top--;
sta[top].k=a[sta[top].root];
}
}
for(int i=1;i<=top;i++)
for(int j=sta[i].l;j<=sta[i].r;j++)
b[j]=sta[i].k,ans+=abs(a[j]-b[j]);
printf("%lld\n",ans);
for(int i=1;i<=n;i++)printf("%lld ",b[i]+i);
return 0;
}

最新文章

  1. iOS App禁止横屏
  2. html5 datalist自动完成
  3. Sbt的使用初步和用sbt插件生成eclipse工程
  4. sizeof usage &amp; big / little endian
  5. 数据库连接池问题 Max Pool Size
  6. ActionBar 的简单使用
  7. linux系统磁盘分区之parted
  8. UICollectionView中Cell左对齐 居中 右对齐 等间距------你想要的,这里都有
  9. DT_修改注册项
  10. Python内置函数(62)——sum
  11. hdu 5183
  12. JQuery官方学习资料(译):遍历
  13. solr7.7.0搜索引擎使用(四)(搜索语法)
  14. 学生管理系统.JavaScript
  15. DIV+CSS:如何编写代码才能更有效率
  16. bzoj 1492
  17. 使用DBMS_SUPPORT包
  18. PAT甲级1049. Counting Ones
  19. 【Json】C#格式化JSON字符串
  20. CentOS 文件搜索find

热门文章

  1. GAN网络原理介绍和代码
  2. Leetcode 216. 组合总和 III
  3. Flask/Tornado/Django
  4. 设计模式-Template(行为模式) 采用 继承的方式 将算法封装在抽象基类中,在子类中实现细节。利用面向对象中的多态实现算法实现细节和高层接口的松耦合。
  5. 函数基础实战之ATM和购物车系统
  6. 【翻译】spring-data 之JdbcTemplate 使用
  7. 安装torch
  8. redis安装等其他操作
  9. springboot热启动中那些不为人知的东东
  10. redis pipeline批量处理提高性能