[BalticOI 2004]Sequence 数字序列
题面
题意:
-
给定一个整数序列
a_1,a_2,...,a_n 。 -
求一个递增序列
b_n ,使得\sum|a_i -b_i| 最小。 -
思路:
这题如果能有部分分提示一下部分思路就更好了。
不递减处理
首先,原题的
令
那么我们把
部分->局部
根据我们初一数学经验,就是在数轴上有
显然,如果
如果
那么我们的目的就是让
左偏树
我们去维护这样一个东西,可以满足:
-
查询中位数
-
合并两个堆
显然左偏树,维护一个大根堆,只要大于
一点小补充
还有,一定会有人有疑问:比如
注意,我们这里是一有递减就合并,那么在加入之前,后面的中位数一定大于前面的中位数。在加入之后,后面的中位数一定小于前面的中位数。好了,那么后面这个堆,只有前一半有用,可以保证。
Code:
时间复杂度
#include<bits/stdc++.h>
#define int long long
#define W while
#define I inline
#define RI register int
#define CI const int
#define DB double
#define ll long long
#define rep(i,a,b) for(RI i=a;i<=b;i++)
#define dow(i,a,b) for(RI i=a;i>=b;--i)
#define edg(i,u,v) for(RI v,i=head[u];v=e[i].to,i;i=e[i].next)
using namespace std;
CI N=1e6+5;
int n,m,ans,top,a[N],sz[N],l[N],r[N],dist[N],lc[N],rc[N],rt[N],val[N];
I int merge(int x,int y){
if(!x||!y) return x|y;a[y]>a[x]&&(swap(x,y),0);rc[x]=merge(rc[x],y); // 注意这里是 a 不要写成 val~!
dist[lc[x]]<dist[rc[x]]&&(swap(lc[x],rc[x]),0);dist[x]=dist[rc[x]]+1;return x;
}
signed main(){
scanf("%lld",&n);rep(i,1,n) scanf("%lld",&a[i]),a[i]-=i,dist[i]=-1; // 不递减
rep(i,1,n){
++top,sz[top]=1,l[top]=r[top]=rt[top]=i,val[top]=a[i];
W((top^1)&&val[top]<val[top-1]){ // 递减就合并
rt[top-1]=rt[top]=merge(rt[top-1],rt[top]);
sz[top-1]+=sz[top],r[top-1]=r[top];top--;
W(sz[top]>(r[top]-l[top]+2)/2) rt[top]=merge(lc[rt[top]],rc[rt[top]]),sz[top]--; // 中位数处理
val[top]=a[rt[top]];
}
}
rep(i,1,top) rep(j,l[i],r[i]) ans+=abs(a[j]-val[i]);printf("%lld\n",ans);
rep(i,1,top) rep(j,l[i],r[i]) printf("%lld ",val[i]+j);return 0;
}