BZOJ 1367 [Baltic2004]sequence【腦洞+可並堆

在黃學長博客看到似乎是某國集大爺的論文例題?

先考慮不嚴格遞增的

考慮對於一段數,如果是遞增的,那麼應該z[i]=t[i]最優,如果是遞減顯然應該區間中的z都等於這個遞減區間的中位數最優,於是可以把整個數列分成一堆遞減的,用堆維護中位數;

對於得到的中位數序列重複上面的操作,顯然可以不斷合併相鄰的堆直到全部遞增


然後發現並不需要每次把整個數列分割成遞減區間,可以直接把每個數當成獨立的區間,和它左邊的區間比較,如果是遞減的就合併求中位數,如果是不下降的就不管【因爲已經滿足了條件】


於是就是用 一個數據結構維護序列 支持 【合併】和【查詢中位數】


講道理的話維護中位數應該用對頂堆吧23333   反正我忘記對頂了直接搞的還是莫名能過【滑稽

#include<bits/stdc++.h>
#define MAXN 1000006
using 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;
}




發佈了123 篇原創文章 · 獲贊 3 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章