# bzoj1367【Baltic2004】sequence

## 1367: [Baltic2004]sequence

Time Limit: 20 Sec  Memory Limit: 64 MB
Submit: 953  Solved: 362
[Submit][Status][Discuss]

7
9
4
8
20
14
15
18

13

## HINT

R=13

#include<iostream>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<cstdio>
#include<algorithm>
#define F(i,j,n) for(int i=j;i<=n;i++)
#define D(i,j,n) for(int i=j;i>=n;i--)
#define ll long long
#define N 1000005
using namespace std;
int n,m,tot,a[N],rt[N],l[N],r[N];
ll ans;
struct HEAP
{
int cnt,l[N],r[N],v[N],d[N],sz[N];
int merge(int x,int y)
{
if (!x||!y) return x+y;
if (v[x]<v[y]) swap(x,y);
r[x]=merge(r[x],y);
if (d[l[x]]<d[r[x]]) swap(l[x],r[x]);
d[x]=d[r[x]]+1;
sz[x]=sz[l[x]]+sz[r[x]]+1;
return x;
}
void pop(int &x)
{
x=merge(l[x],r[x]);
}
int new_heap(int x)
{
cnt++;
v[cnt]=x;
sz[cnt]=1;
l[cnt]=r[cnt]=0;d[cnt]=1;
return cnt;
}
}heap;
{
int x=0,f=1;char ch=getchar();
while (ch<'0'||ch>'9'){if (ch=='-') f=-1;ch=getchar();}
while (ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
return x*f;
}
int main()
{
F(i,1,n)
{
tot++;
rt[tot]=heap.new_heap(a[i]);
l[tot]=r[tot]=i;
while (tot>1&&heap.v[rt[tot-1]]>heap.v[rt[tot]])
{
tot--;
rt[tot]=heap.merge(rt[tot],rt[tot+1]);
r[tot]=r[tot+1];
while (heap.sz[rt[tot]]>(r[tot]-l[tot]+2)/2) heap.pop(rt[tot]);
}
}
F(i,1,tot)
{
int tmp=heap.v[rt[i]];
F(j,l[i],r[i]) ans+=abs(a[j]-tmp);
}
printf("%lld\n",ans);
return 0;
}


#### bzoj1367 [Baltic2004]sequence [左偏树]

2015-06-17 12:31:02

#### bzoj 1367: [Baltic2004]sequence（中位数+可并堆）

2016-05-08 17:16:14

#### BZOJ1367 [Baltic2004]sequence

2017-02-24 15:18:43

#### BZOJ 1367([Baltic2004]sequence-左偏树+中位数贪心)

2013-07-13 15:23:34

#### [Baltic2004]sequence。。。初学左偏树

2010-12-18 17:58:00

#### [BZOJ1367] [Baltic2004]sequence

2017-08-02 22:14:52

#### bzoj1367 [Baltic2004]sequence

2017-04-18 09:44:59

#### 【BZOJ1367】【Baltic2004】sequence

2018-03-18 15:43:17

#### bzoj1367: [Baltic2004]sequence

2016-01-19 21:30:02

#### [BZOJ1367][Baltic2004]sequence（可并堆+中位数）

2018-04-12 17:49:44