写在赤石之前
月考刚结束,脑袋有点不清楚。如有雷同,就当我是蒟蒻。如果这个理论有人提出来过,那么就当我啥理论没提出来。未归紫衫。这是妥妥的赤石科技,不建议在OI中使用。
正文
神人的发明背景
每道题我都想不到线性做法!!!这实在是令人太恼火了,既然 priority_queue 也叫 queue(并非),所以,我来报复社会乐。让你的 queue 使用中由 加几个 。
前置芝士
由于本文章以 priority_queue 为基础,也就是堆为基础,请没有基础的人左转 OI-WIKI 堆界面。
神人的推导
首先,二叉堆,即优先队列,是一棵完全二叉树,通过不断维护,使得优先级最高的始终位于堆顶,一般使用都以数值为优先级。
而队列,又称 FIFO 表,先进先出,我们可以认为这里的优先级为入队顺序,结合广搜知识,大抵也就是广度,可以发现,队列的队头一定是入队顺序最早的一个,且内部顺序与入队顺序有关,所以可以认为,队列是一个以入队顺序为优先级的小根堆。
实现
前言
使用 priority_queue 的话可以直接通过重载运算符,这是无话可说的。
实现之前
原来的二叉堆,可以使用,在基础上改一改就好。
因为刚学完的线段树,那么存树就直接开个 数组。
code:
struct node{
int a,b;
bool operator<(const node& b) const {
return this->b > b.b;
}
}w[100010];
int lst=0,tot=0; 堆顶(队头)
code:
int top(){
return w[1].a;
}插入/入队
在插入之前,最重要的东西就是修复(modify)。
与堆一样,以入队顺序为优先级:
void modify(int x){
if(x==1 or !(w[x]<w[x/2]))return ;
swap(w[x],w[x/2]);
modify(x/2);
}
void push(int x){
w[++tot].a=x;
w[tot].b=lst+1;
lst=w[tot].b;
modify(tot);
}删顶/出队
当然不能直接删顶。
如直接把堆顶擦掉,它将会分裂成两棵树,此刻会遇到大麻烦。 ——《深入浅出程序设计竞赛·进阶篇》第五章
还是如堆那样,我们先交换堆顶堆底,然后修复。
但是此时优先级改成了入队顺序。
代码实现
void repair(int x){
if(x*2>tot)return ;
int tar=x*2;
if(x*2+1<=tot){
tar=w[x*2]<w[x*2+1]?x*2:x*2+1;
}
if(w[tar]<w[x]){
swap(w[x],w[tar]);
repair(tar);
}
}
void pop(){
swap(w[1],w[tot--]);
repair(1);
}全代码 (B3616)
#include<bits/stdc++.h>
using namespace std;
struct node{
int a, b;
bool operator<(const node& other) const {
return this->b < other.b;
}
}w[100010];
int lst=0, tot=0;
void modify(int x){
if(x == 1) return;
if(w[x] < w[x/2]){
swap(w[x], w[x/2]);
modify(x/2);
}
}
void push(int x){
w[++tot].a = x;
w[tot].b = ++lst;
modify(tot);
}
void repair(int x){
if(x*2 > tot) return;
int tar = x*2;
if(x*2+1 <= tot && w[x*2+1] < w[tar]){
tar = x*2 + 1;
}
if(w[tar] < w[x]){
swap(w[x], w[tar]);
repair(tar);
}
}
void pop(){
if(tot == 0) return;
swap(w[1], w[tot--]);
repair(1);
}
int top(){
return w[1].a;
}
int main(){//1插2删3查顶4查大小
int q;
cin >> q;
while(q--){
int op, x;
cin >> op;
string ans = "";
if(op == 1){
cin >> x;
push(x);
}
else if(op == 2){
if(tot == 0){
ans = "ERR_CANNOT_POP";
}
else{
pop();
}
}
else if(op == 3){
if(tot == 0){
ans = "ERR_CANNOT_QUERY";
}
else{
ans = to_string(top());
}
}
else if(op == 4){
ans = to_string(tot);
}
if(!ans.empty()){
cout << ans <<endl;
}
}
return 0;
}总体而言(时间复杂度)
很抽象就是了,时间复杂度让我们看一下。
push
由于我们每次插入的时候,都会插在堆底,而此时新节点的优先级又是小根堆意义下的最小,所以不会触发 modify,不难证明,此时复杂度估计为 。
top/front
每次只是查询堆顶,时间复杂度为 。
pop
每次都会将堆顶与堆底互换,然后从顶向下维护,在最坏情况下,可达 。
总结
纯粹的赤石科技,实现与手写数组慢亿点,但还是有价值的(大雾)。实际使用时最好特判 ,也就是判断其非空。