BZOJ 1367 [Baltic2004]sequence【脑洞+可并堆

来源:互联网 发布:北京摄影函授学院知乎 编辑:程序博客网 时间:2024/06/16 17:20

在黄学长博客看到似乎是某国集大爷的论文例题?

先考虑不严格递增的

考虑对于一段数,如果是递增的,那么应该z[i]=t[i]最优,如果是递减显然应该区间中的z都等于这个递减区间的中位数最优,于是可以把整个数列分成一堆递减的,用堆维护中位数;

对于得到的中位数序列重复上面的操作,显然可以不断合并相邻的堆直到全部递增


然后发现并不需要每次把整个数列分割成递减区间,可以直接把每个数当成独立的区间,和它左边的区间比较,如果是递减的就合并求中位数,如果是不下降的就不管【因为已经满足了条件】


于是就是用 一个数据结构维护序列 支持 【合并】和【查询中位数】


讲道理的话维护中位数应该用对顶堆吧23333   反正我忘记对顶了直接搞的还是莫名能过【滑稽

#include<bits/stdc++.h>#define MAXN 1000006using namespace std;int n;inline int read(){register char ch = getchar();while(!isdigit(ch))ch = getchar();register int rtn = 0;while(isdigit(ch))rtn = rtn*10 + ch - '0' , ch = getchar();return rtn;}struct Node{Node *Son,*Brother;int key,size,sum;Node(){}Node(Node *Son,Node * Brother,int key,int size):Son(Son),Brother(Brother),key(key),size(size),sum(key){}}ttt[MAXN],*root[MAXN],*null;int cnt_node;inline Node * New_node(int k){return &(ttt[++cnt_node] = Node(null,null,k,1));}inline Node * merge(Node *a,Node *b){if(a==null)return b;if(b==null)return a;if(a->key < b->key)swap(a,b);a->size += b->size;a->sum += b->sum;a->Brother = null;b->Brother = a->Son;a->Son = b;return a;}inline Node * pop(Node *a){static queue<Node * > q;for(Node *now = a->Son;now != null;now = now->Brother)q.push(now);while(q.size() > 1u){Node *x = q.front();q.pop();Node *y = q.front();q.pop();q.push(merge(x,y));}Node * rtn = q.front();q.pop();return rtn;}Node * rec[MAXN];int lth[MAXN];int cnt_heap;int a[MAXN];int main(){n = read();null = new Node(0,0,0,0);for(int i=1;i<=n;++i){rec[++cnt_heap] = New_node(a[i] = read() - i);lth[cnt_heap] = 1;while(cnt_heap>1 && rec[cnt_heap]->key < rec[cnt_heap-1]->key){lth[cnt_heap-1] += lth[cnt_heap];rec[cnt_heap-1] = merge(rec[cnt_heap],rec[cnt_heap-1]);--cnt_heap;while((lth[cnt_heap]>>1)+1 < rec[cnt_heap]->size)rec[cnt_heap] = pop(rec[cnt_heap]);}}long long ans = 0;for(int i=1,id=1;i<=cnt_heap;++i){long long tmp = rec[i]->key;for(int j=1;j<=lth[i];++j,++id)ans += (tmp-a[id]>=0?tmp-a[id]:a[id]-tmp);}printf("%lld",ans);return 0;}




0 0
原创粉丝点击